Just left to improve my code.
android:permission="android.permission.MOBIADS"
android:readPermission="android.permission.READ_MOBIADS"
android:syncable="false"
- android:writePermission="android.permission.WRITE_MOBIADS" >
+ android:writePermission="android.permission.WRITE_MOBIADS"
+ android:process=":mobiadsservice" >
<grant-uri-permission android:pathPattern=".*" />
</provider>
- <!--
- <provider
- android:process="string" When having my service, here I should write the service process name
- </provider>-->
</application>
--- /dev/null
+/** Automatically generated file. DO NOT MODIFY */
+package de.android.mobiads;
+
+public final class BuildConfig {
+ public final static boolean DEBUG = true;
+}
\ No newline at end of file
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
-import android.webkit.CookieManager;
-import android.webkit.CookieSyncManager;
import android.widget.EditText;
public class MobiAdsLoginActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- CookieSyncManager.createInstance(this);
currentPolicy = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
setContentView(R.layout.main);
case HttpStatus.SC_OK:
String cookie = httpResponse.getLastHeader(SETCOOKIEFIELD).getValue();
if (cookie != null) {
- CookieManager.getInstance().setCookie(getResources().getString(R.string.url_web),cookie);
- CookieSyncManager.getInstance().sync();
+ cookie = cookie.split(";")[0];
//Go to the next activity
StrictMode.setThreadPolicy(currentPolicy);
- this.startActivity(new Intent("android.intent.action.MOBIADS").
- setComponent(new ComponentName("de.android.mobiads", "de.android.mobiads.MobiAdsMainActivity")));
+ Intent intent = new Intent("android.intent.action.MOBIADS").
+ setComponent(new ComponentName("de.android.mobiads", "de.android.mobiads.MobiAdsMainActivity"));
+ intent.putExtra("cookie", cookie);
+ this.startActivity(intent);
} else {
Log.e(TAG, "There must be a weird issue with the server because... There is not cookie!!!!");
createErrorDialog(R.string.error_dialog_connection_error);
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
-import android.widget.TextView;
-import android.widget.Toast;
public class MobiAdsMainActivity extends Activity {
/** Messenger for communicating with service. */
Messenger mService = null;
/** Flag indicating whether we have called bind on the service. */
boolean mIsBound;
- /** Some text view we are using to show state information. */
- TextView mCallbackText;
/**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger(new IncomingHandler());
- private static final String TAG = "MobiAdsMainActivity";
+
+ private String cookie;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
+ Bundle bundle = getIntent().getExtras();
+ this.cookie = bundle.getString("cookie");
super.onCreate(savedInstanceState);
setContentView(R.layout.mobiadsmain);
}
public void handleMessage(Message msg) {
switch (msg.what) {
case MobiAdsService.MSG_SET_VALUE:
- mCallbackText.setText("Received from service: " + msg.arg1);
break;
default:
super.handleMessage(msg);
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = new Messenger(service);
- mCallbackText.setText("Attached.");
// We want to monitor the service for as long as we are
// connected to it.
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
}
-
- // As part of the sample, tell the user what happened.
- Toast.makeText(MobiAdsMainActivity.this, R.string.remote_service_started,
- Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
- mCallbackText.setText("Disconnected.");
-
- // As part of the sample, tell the user what happened.
- Toast.makeText(MobiAdsMainActivity.this, R.string.remote_service_stopped,
- Toast.LENGTH_SHORT).show();
}
};
boolean prueba = bindService(new Intent(MobiAdsMainActivity.this,
MobiAdsService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
- mCallbackText.setText("Binding.");
}
public void onClickBind(View v) {
- mCallbackText = new TextView(this);
this.doBindService();
}
public void onClickStartService(View v) {
- this.startService(new Intent(MobiAdsMainActivity.this, MobiAdsService.class));
+ Intent intent = new Intent(MobiAdsMainActivity.this, MobiAdsService.class);
+ intent.putExtra("cookie", this.cookie);
+ this.startService(intent);
}
}
private LocationManager locationManager;
private LocationListener locationListener;
-
-
- @Override
- public void onCreate() {
- //There should not be more than one thread using mobiAdsBatch field, see:
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ final String cookie = intent.getStringExtra("cookie");
+
+ //There should not be more than one thread using mobiAdsBatch field, see:
//http://developer.android.com/guide/topics/fundamentals/services.html#LifecycleCallbacks
//Otherwise there could be issues about sharing this field...
this.mobiAdsBatch = new MobiAdsBatch(this.getResources().getString(R.string.user_agent_web_service),
- this.getResources().getString(R.string.encoded_web_service), this);
+ this.getResources().getString(R.string.encoded_web_service), this, cookie);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedRequired(true);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
+
// Acquire a reference to the system Location Manager
this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// Display a notification about us starting.
showNotification();
+
+ return super.onStartCommand(intent, flags, startId);
}
-
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.util.Log;
-import android.webkit.CookieManager;
-import android.webkit.CookieSyncManager;
-import de.android.mobiads.R;
import de.android.mobiads.provider.Indexer;
public class MobiAdsBatch {
private final String mobiAdsCookie;
- public MobiAdsBatch (String userAgent, String encoded, Context context) {
+ public MobiAdsBatch (String userAgent, String encoded, Context context, String cookie) {
this.context = context;
this.httpClient = AndroidHttpClient.newInstance(userAgent);
-
+ this.mobiAdsCookie = cookie;
this.httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, encoded);
this.httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
- CookieSyncManager.createInstance(this.context);
- this.mobiAdsCookie = CookieManager.getInstance().getCookie(this.context.getResources().getString(R.string.url_web));
}
//In case of any error, remove the index database and the file
//or chunk successfully stored before the error.
try {
+ Log.i("MobiAdsBatch","delete");
MobiAdsBatch.this.context.getContentResolver().delete(uriInsert, null, null);
MobiAdsBatch.this.context.deleteFile((String) objects.get("id"));
} catch (Throwable e2) {
if (e1 instanceof RuntimeException) {
throw (RuntimeException) e1;
}
- if (e1 instanceof Exception) {
+ if (e1 instanceof IOException) {
throw (IOException) e1;
}
//throwing Throwable. At least the original exception is not lost :/
}
}
break;
- case HttpStatus.SC_UNAUTHORIZED:
- //ERROR IN USERNAME OR PASSWORD
- throw new SecurityException("Unauthorized access: error in username or password.");
- case HttpStatus.SC_BAD_REQUEST:
- //WHAT THE HECK ARE YOU DOING?
- throw new IllegalArgumentException("Bad request.");
- default:
- throw new IllegalArgumentException("Error while retrieving the HTTP status line.");
+ case HttpStatus.SC_UNAUTHORIZED:
+ //ERROR IN USERNAME OR PASSWORD
+ throw new SecurityException("Unauthorized access: error in username or password.");
+ case HttpStatus.SC_BAD_REQUEST:
+ //WHAT THE HECK ARE YOU DOING?
+ throw new IllegalArgumentException("Bad request.");
+ default:
+ throw new IllegalArgumentException("Error while retrieving the HTTP status line.");
}
}
return builder;
Uri uri = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer" + "/idad/" + objects.get("id"));
synchronized (MobiAdsBatch.this) {
+ //getContentResolver().query method never returns Cursor with null value.
+ //TODO: review my code in order to find more cases like this. :(
+ //Be aware with the RunTimeExceptions. Apparently Java needs try/catch blocks in everywhere...
Cursor cursor = MobiAdsBatch.this.context.getContentResolver().query(uri, null, null, null, null);
-
- if (cursor != null) {
+ try {
if (!cursor.moveToFirst()) {
//If the advertisement was not stored on the database
ContentValues values = new ContentValues();
values.put(Indexer.Index.COLUMN_NAME_ID_AD, new Integer((String) objects.get("id")));
values.put(Indexer.Index.COLUMN_NAME_PATH, (String) objects.get("id"));
+ //This method may throw SQLiteException (as a RunTimeException). So, without a try/catch block
+ //there could be a leaked cursor...
+ //TODO: review code looking for more cases like this one...
updated = MobiAdsBatch.this.context.getContentResolver().insert(Indexer.Index.CONTENT_ID_URI_BASE, values);
}
+ } finally {
cursor.close();
}
}
*/
@Override
public void onCreate(SQLiteDatabase db) {
+ Log.i("IndexerOpenHelper", "onCreate");
db.execSQL("CREATE TABLE " + Indexer.Index.TABLE_NAME + " ("
+ Indexer.Index._ID + " INTEGER PRIMARY KEY, "
+ Indexer.Index.COLUMN_NAME_ID_AD + " INTEGER" + " UNIQUE" + " NOT NULL,"
+ ");");
}
+ @Override
+ public void close() {
+ super.close();
+ Log.i("IndexerOpenHelper", "close");
+ }
/**
*
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
+import android.database.sqlite.SQLiteReadOnlyDatabaseException;
import android.net.Uri;
import android.text.TextUtils;
+import android.util.Log;
+
/**
*
*/
@Override
public boolean onCreate() {
+ Log.i("IndexerProvider", "onCreate");
// Creates a new helper object. Note that the database itself isn't opened until
// something tries to access it, and it's only created if it doesn't already exist.
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
-
// Constructs a new query builder and sets its table name
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(Indexer.Index.TABLE_NAME);
orderBy // The sort order
);
-
+ if (c == null) {
+ // If the cursor is null, throw an exception
+ throw new SQLiteReadOnlyDatabaseException("Unable to query " + uri);
+ }
// Tells the Cursor what URI to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
@Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
-
// Opens the database object in "write" mode.
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
// Returns the number of rows updated.
return count;
}
-
+
+ @Override
+ public void shutdown() {
+ mOpenHelper.close();
+ }
}