MobiAds android application working smoothly.
authorgumartinm <gustavo@gumartinm.name>
Fri, 30 Mar 2012 05:28:22 +0000 (07:28 +0200)
committergumartinm <gustavo@gumartinm.name>
Fri, 30 Mar 2012 05:28:22 +0000 (07:28 +0200)
Just left to improve my code.

Android/MobiAds/AndroidManifest.xml
Android/MobiAds/gen/de/android/mobiads/BuildConfig.java [new file with mode: 0644]
Android/MobiAds/src/de/android/mobiads/MobiAdsLoginActivity.java
Android/MobiAds/src/de/android/mobiads/MobiAdsMainActivity.java
Android/MobiAds/src/de/android/mobiads/MobiAdsService.java
Android/MobiAds/src/de/android/mobiads/batch/MobiAdsBatch.java
Android/MobiAds/src/de/android/mobiads/provider/IndexerOpenHelper.java
Android/MobiAds/src/de/android/mobiads/provider/IndexerProvider.java

index 41b37c2..9646322 100644 (file)
                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>
     
diff --git a/Android/MobiAds/gen/de/android/mobiads/BuildConfig.java b/Android/MobiAds/gen/de/android/mobiads/BuildConfig.java
new file mode 100644 (file)
index 0000000..5ab5a24
--- /dev/null
@@ -0,0 +1,6 @@
+/** 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
index cde859a..6f0ccc8 100644 (file)
@@ -27,8 +27,6 @@ import android.os.Bundle;
 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 {
@@ -40,7 +38,6 @@ 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);
@@ -83,12 +80,13 @@ public class MobiAdsLoginActivity extends Activity {
                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);
index 84dfe06..8cdab96 100644 (file)
@@ -12,26 +12,25 @@ import android.os.Message;
 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);
     }    
@@ -44,7 +43,6 @@ public class MobiAdsMainActivity extends Activity {
         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);
@@ -66,7 +64,6 @@ public class MobiAdsMainActivity extends Activity {
             // 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.
@@ -86,21 +83,12 @@ public class MobiAdsMainActivity extends Activity {
                 // 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();
         }
     };
 
@@ -111,12 +99,10 @@ public class MobiAdsMainActivity extends Activity {
         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();
     }
     
@@ -131,6 +117,8 @@ public class MobiAdsMainActivity extends Activity {
     
     
     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);
     }
 }
index 03642b6..3e4f2fc 100644 (file)
@@ -41,16 +41,16 @@ public class MobiAdsService extends Service {
     
     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);
@@ -64,6 +64,7 @@ public class MobiAdsService extends Service {
         criteria.setSpeedRequired(true);
         criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
         
+        
         // Acquire a reference to the system Location Manager
         this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
 
@@ -102,9 +103,10 @@ public class MobiAdsService extends 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
index b9fdd74..025ab32 100644 (file)
@@ -30,9 +30,6 @@ import android.location.Location;
 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 {
@@ -44,15 +41,13 @@ 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));
        }
        
        
@@ -123,6 +118,7 @@ public class MobiAdsBatch {
                                                                //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) {
@@ -138,7 +134,7 @@ public class MobiAdsBatch {
                                                                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 :/
@@ -192,14 +188,14 @@ public class MobiAdsBatch {
                                                }
                                        }
                                        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; 
@@ -263,16 +259,22 @@ public class MobiAdsBatch {
                        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();
                                }
                        }
index fff4ccc..ab42ba0 100644 (file)
@@ -25,6 +25,7 @@ public class IndexerOpenHelper extends SQLiteOpenHelper {
      */
     @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,"
@@ -32,6 +33,11 @@ public class IndexerOpenHelper extends SQLiteOpenHelper {
                                + ");");
        }
 
+    @Override
+    public void close() {
+       super.close();
+       Log.i("IndexerOpenHelper", "close");
+    }
 
     /**
      *
index 4cf3b74..d616500 100644 (file)
@@ -9,8 +9,11 @@ import android.database.Cursor;
 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;
+
 
 /**
  *
@@ -81,6 +84,7 @@ public class IndexerProvider extends ContentProvider {
         */
        @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.
@@ -252,7 +256,6 @@ public class IndexerProvider extends ContentProvider {
        @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);
@@ -320,7 +323,10 @@ public class IndexerProvider extends ContentProvider {
                        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;
@@ -349,7 +355,6 @@ public class IndexerProvider extends ContentProvider {
        @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;
@@ -418,5 +423,9 @@ public class IndexerProvider extends ContentProvider {
         // Returns the number of rows updated.
         return count;
        }
-
+       
+       @Override
+       public void shutdown() {
+               mOpenHelper.close();
+       }
 }