From: gumartinm Date: Sat, 15 Dec 2012 03:45:05 +0000 (+0100) Subject: No time for comments. Loads of changes. X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=c423aa94b8b0456b43375485ba37d8cb04ffd6b8;p=JavaForFun No time for comments. Loads of changes. Mainly indentation changes... That sucks, but I have not time to sort indentation changes from the real ones... --- diff --git a/Android/MobiAdsReloaded/gen/de/android/mobiads/R.java b/Android/MobiAdsReloaded/gen/de/android/mobiads/R.java index 52e2c59..6a5ece9 100644 --- a/Android/MobiAdsReloaded/gen/de/android/mobiads/R.java +++ b/Android/MobiAdsReloaded/gen/de/android/mobiads/R.java @@ -8,6 +8,12 @@ package de.android.mobiads; public final class R { + public static final class array { + public static final int meters_update_rate_human_value=0x7f050001; + public static final int meters_update_rate_value=0x7f050000; + public static final int time_update_rate_human_value=0x7f050003; + public static final int time_update_rate_value=0x7f050002; + } public static final class attr { } public static final class drawable { @@ -17,17 +23,17 @@ public final class R { public static final int wheelnotification=0x7f020003; } public static final class id { - public static final int ads_entry_icon=0x7f070000; - public static final int ads_entry_text=0x7f070002; - public static final int ads_entry_title=0x7f070001; - public static final int frameLayout1=0x7f070003; - public static final int frameLayout2=0x7f070006; - public static final int login_button=0x7f070007; - public static final int menuads_login=0x7f070008; - public static final int menuads_settings=0x7f070009; - public static final int password=0x7f070005; - public static final int selectedmenu_remove=0x7f07000a; - public static final int username=0x7f070004; + public static final int ads_entry_icon=0x7f080000; + public static final int ads_entry_text=0x7f080002; + public static final int ads_entry_title=0x7f080001; + public static final int frameLayout1=0x7f080003; + public static final int frameLayout2=0x7f080006; + public static final int login_button=0x7f080007; + public static final int menuads_login=0x7f080008; + public static final int menuads_settings=0x7f080009; + public static final int password=0x7f080005; + public static final int selectedmenu_remove=0x7f08000a; + public static final int username=0x7f080004; } public static final class layout { public static final int ads_entry_list_item=0x7f030000; @@ -35,45 +41,53 @@ public final class R { public static final int main=0x7f030002; } public static final class menu { - public static final int menuads=0x7f060000; - public static final int selectedmenuads=0x7f060001; + public static final int menuads=0x7f070000; + public static final int selectedmenuads=0x7f070001; } public static final class string { - public static final int alert_dialog_logged=0x7f050004; - public static final int alert_dialog_not_logged=0x7f050005; - public static final int app_description=0x7f050003; - public static final int app_name=0x7f050002; - public static final int button_cancel=0x7f050011; - public static final int button_localads=0x7f050012; - public static final int button_login=0x7f05000a; - public static final int button_messagebind=0x7f05000b; - public static final int button_messagelistlocalads=0x7f05000f; - public static final int button_messagestartservice=0x7f05000e; - public static final int button_messagestopservice=0x7f05000d; - public static final int button_messageunbind=0x7f05000c; - public static final int button_ok=0x7f050010; - public static final int desc=0x7f05001e; - public static final int encoded_web_service=0x7f05001d; - public static final int error_dialog_connection_error=0x7f050006; - public static final int error_dialog_no_local_ads=0x7f050022; - public static final int error_dialog_userpwd_error=0x7f050007; - public static final int header_bar=0x7f050000; - public static final int menuads_login=0x7f050021; - public static final int menuads_remove=0x7f05001f; - public static final int menuads_settings=0x7f050020; - public static final int new_ads=0x7f050001; - public static final int password=0x7f050009; - public static final int remote_service_content_empty_notification=0x7f050016; - public static final int remote_service_content_notification=0x7f050015; - public static final int remote_service_new_ads=0x7f050013; - public static final int remote_service_received_ad_notification=0x7f050014; - public static final int remote_service_started_notification=0x7f050017; - public static final int remote_service_stopped_notification=0x7f050018; - public static final int remote_service_title_notification=0x7f050019; - public static final int url_login_web_service=0x7f05001a; - public static final int url_web=0x7f05001b; - public static final int user_agent_web_service=0x7f05001c; - public static final int username=0x7f050008; + public static final int alert_dialog_logged=0x7f060004; + public static final int alert_dialog_not_logged=0x7f060005; + public static final int app_description=0x7f060003; + public static final int app_name=0x7f060002; + public static final int button_cancel=0x7f060011; + public static final int button_localads=0x7f060012; + public static final int button_login=0x7f06000a; + public static final int button_messagebind=0x7f06000b; + public static final int button_messagelistlocalads=0x7f06000f; + public static final int button_messagestartservice=0x7f06000e; + public static final int button_messagestopservice=0x7f06000d; + public static final int button_messageunbind=0x7f06000c; + public static final int button_ok=0x7f060010; + public static final int desc=0x7f060020; + public static final int encoded_web_service=0x7f06001f; + public static final int error_dialog_connection_error=0x7f060006; + public static final int error_dialog_no_local_ads=0x7f060024; + public static final int error_dialog_userpwd_error=0x7f060007; + public static final int header_bar=0x7f060000; + public static final int menuads_login=0x7f060023; + public static final int menuads_remove=0x7f060021; + public static final int menuads_settings=0x7f060022; + public static final int meters_update_rate_preference_summary=0x7f060028; + public static final int meters_update_rate_preference_title=0x7f060027; + public static final int new_ads=0x7f060001; + public static final int password=0x7f060009; + public static final int remote_service_content_empty_notification=0x7f060016; + public static final int remote_service_content_notification=0x7f060015; + public static final int remote_service_new_ads=0x7f060013; + public static final int remote_service_received_ad_notification=0x7f060014; + public static final int remote_service_started_notification=0x7f060017; + public static final int remote_service_stopped_notification=0x7f060018; + public static final int remote_service_title_notification=0x7f060019; + public static final int service_preference_title=0x7f060025; + public static final int service_preference_title_summary=0x7f060026; + public static final int time_update_rate_preference_summary=0x7f06002a; + public static final int time_update_rate_preference_title=0x7f060029; + public static final int url_api_web_services=0x7f06001b; + public static final int url_images=0x7f06001c; + public static final int url_login_web_service=0x7f06001a; + public static final int url_web=0x7f06001d; + public static final int user_agent_web_service=0x7f06001e; + public static final int username=0x7f060008; } public static final class xml { public static final int preferences=0x7f040000; diff --git a/Android/MobiAdsReloaded/project.properties b/Android/MobiAdsReloaded/project.properties index e484b3c..0c9830a 100644 --- a/Android/MobiAdsReloaded/project.properties +++ b/Android/MobiAdsReloaded/project.properties @@ -11,4 +11,4 @@ #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt # Project target. -target=Google Inc.:Google APIs:16 +target=Google Inc.:Google APIs:17 diff --git a/Android/MobiAdsReloaded/res/values/arrays.xml b/Android/MobiAdsReloaded/res/values/arrays.xml new file mode 100644 index 0000000..fa18bd4 --- /dev/null +++ b/Android/MobiAdsReloaded/res/values/arrays.xml @@ -0,0 +1,33 @@ + + + + 10 + 20 + 30 + 40 + 50 + + + 10 meters + 20 meters + 30 meters + 40 meters + 50 meters + + + 0 + 1 + 2 + 5 + 10 + 20 + + + 0 minutes + 1 minute + 2 minutes + 5 minutes + 10 minutes + 20 minutes + + \ No newline at end of file diff --git a/Android/MobiAdsReloaded/res/values/strings.xml b/Android/MobiAdsReloaded/res/values/strings.xml index 57b259a..050cfd3 100644 --- a/Android/MobiAdsReloaded/res/values/strings.xml +++ b/Android/MobiAdsReloaded/res/values/strings.xml @@ -27,6 +27,8 @@ MobiAds Service Stopped MobiAds Service http://users.mobiads.gumartinm.name/userfront.php/api/login/auth.json + http://users.mobiads.gumartinm.name/userfront.php/api/ + http://companies.mobiads.gumartinm.name/uploads/images/ users.mobiads.gumartinm.name MobiAds/1.0 UTF-8 @@ -35,4 +37,10 @@ Settings Login You have no downloaded ads. + Service started + Start or stop downloading ads. + Meters update rate + Control the frequency of location updates. Lower values increase power consumption. + Time update rate + Elapsed time between location updates. Lower values increase power consumption. \ No newline at end of file diff --git a/Android/MobiAdsReloaded/res/xml/preferences.xml b/Android/MobiAdsReloaded/res/xml/preferences.xml index 48c7aba..b2acfb3 100644 --- a/Android/MobiAdsReloaded/res/xml/preferences.xml +++ b/Android/MobiAdsReloaded/res/xml/preferences.xml @@ -5,7 +5,30 @@ + + \ No newline at end of file diff --git a/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsLoginActivity.java b/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsLoginActivity.java index 68586ed..d6620d3 100644 --- a/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsLoginActivity.java +++ b/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsLoginActivity.java @@ -32,138 +32,142 @@ import android.view.View; import android.widget.EditText; public class MobiAdsLoginActivity extends Activity { - private static final String TAG = "MobiAdsLoginActivity"; - private static final String SETCOOKIEFIELD = "Set-Cookie"; - private StrictMode.ThreadPolicy currentPolicy; - + private static final String TAG = "MobiAdsLoginActivity"; + private static final String SETCOOKIEFIELD = "Set-Cookie"; + private StrictMode.ThreadPolicy currentPolicy; + /** Called when the activity is first created. */ @Override - public void onCreate(Bundle savedInstanceState) { + public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); currentPolicy = StrictMode.getThreadPolicy(); StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX); setContentView(R.layout.login); } - - public void onClickLogin(View v) { - final EditText password = (EditText) findViewById(R.id.password); - final EditText username = (EditText) findViewById(R.id.username); - final HttpClient httpClient = new DefaultHttpClient(); - String pruba = getResources().getString(R.string.url_login_web_service); - final HttpPost httpPost = new HttpPost(pruba); - HttpEntity httpEntity = null; - HttpResponse httpResponse = null; - final List formParams = new ArrayList(2); - - - httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, getResources().getString(R.string.encoded_web_service)); - httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, getResources().getString(R.string.user_agent_web_service)); - httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); - //TODO: RESTful Web Service must use JSON instead of signin array :( - formParams.add(new BasicNameValuePair("signin[username]", username.getText().toString())); - formParams.add(new BasicNameValuePair("signin[password]", password.getText().toString())); + + public void onClickLogin(final View v) { + final EditText password = (EditText) findViewById(R.id.password); + final EditText username = (EditText) findViewById(R.id.username); + final HttpClient httpClient = new DefaultHttpClient(); + final HttpPost httpPost = new HttpPost(getResources().getString(R.string.url_login_web_service)); + HttpEntity httpEntity = null; + HttpResponse httpResponse = null; + final List formParams = new ArrayList(2); + + + httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, getResources().getString(R.string.encoded_web_service)); + httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, getResources().getString(R.string.user_agent_web_service)); + httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); + //TODO: RESTful Web Service must use JSON instead of signin array :( + formParams.add(new BasicNameValuePair("signin[username]", username.getText().toString())); + formParams.add(new BasicNameValuePair("signin[password]", password.getText().toString())); try { - httpEntity = new UrlEncodedFormEntity(formParams, getResources().getString(R.string.encoded_web_service)); - httpPost.setEntity(httpEntity); - httpResponse = httpClient.execute(httpPost); - } catch (UnsupportedEncodingException e) { - Log.e(TAG, "Error while encoding POST parameters.", e); - return; - } catch (ClientProtocolException e) { - Log.e(TAG, "Error while executing HTTP client connection.", e); - createErrorDialog(R.string.error_dialog_connection_error); - return; - } catch (IOException e) { - Log.e(TAG, "Error while executing HTTP client connection.", e); - createErrorDialog(R.string.error_dialog_connection_error); - return; - } finally { - httpClient.getConnectionManager().shutdown(); - } - + httpEntity = new UrlEncodedFormEntity(formParams, getResources().getString(R.string.encoded_web_service)); + httpPost.setEntity(httpEntity); + httpResponse = httpClient.execute(httpPost); + } catch (final UnsupportedEncodingException e) { + Log.e(TAG, "Error while encoding POST parameters.", e); + //finally block runs just before returning from this code and that is what we want. + return; + } catch (final ClientProtocolException e) { + Log.e(TAG, "Error while executing HTTP client connection.", e); + createErrorDialog(R.string.error_dialog_connection_error); + //finally block runs just before returning from this code and that is what we want. + return; + } catch (final IOException e) { + Log.e(TAG, "Error while executing HTTP client connection.", e); + createErrorDialog(R.string.error_dialog_connection_error); + //finally block runs just before returning from this code and that is what we want. + return; + } finally { + //this code is used always even when returning from one of the above blocks. + httpClient.getConnectionManager().shutdown(); + } + if (httpResponse != null) { switch (httpResponse.getStatusLine().getStatusCode()) { - case HttpStatus.SC_OK: - String cookie = httpResponse.getLastHeader(SETCOOKIEFIELD).getValue(); - if (cookie != null) { - cookie = cookie.split(";")[0]; - //Go to the next activity - StrictMode.setThreadPolicy(currentPolicy); - Cookie.setCookie(cookie); - this.finish(); - } 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); - } - break; - case HttpStatus.SC_UNAUTHORIZED: - //Username or password is incorrect - createErrorDialog(R.string.error_dialog_userpwd_error); - break; - case HttpStatus.SC_BAD_REQUEST: - //What the heck are you doing? - createErrorDialog(R.string.error_dialog_userpwd_error); - break; - default: - Log.e(TAG, "Error while retrieving the HTTP status line."); - createErrorDialog(R.string.error_dialog_connection_error); - break; - } - } + case HttpStatus.SC_OK: + String cookie = httpResponse.getLastHeader(SETCOOKIEFIELD).getValue(); + if (cookie != null) { + cookie = cookie.split(";")[0]; + //Go to the next activity + StrictMode.setThreadPolicy(currentPolicy); + Cookie.setCookie(cookie); + this.finish(); + } 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); + } + break; + case HttpStatus.SC_UNAUTHORIZED: + //Username or password is incorrect + createErrorDialog(R.string.error_dialog_userpwd_error); + break; + case HttpStatus.SC_BAD_REQUEST: + //What the heck are you doing? + createErrorDialog(R.string.error_dialog_userpwd_error); + break; + default: + Log.e(TAG, "Error while retrieving the HTTP status line."); + createErrorDialog(R.string.error_dialog_connection_error); + break; + } + } else { - Log.e(TAG, "No response? This should never have happened."); - createErrorDialog(R.string.error_dialog_connection_error); + Log.e(TAG, "No response? This should never have happened."); + createErrorDialog(R.string.error_dialog_connection_error); } } - - public void onClickLocalAds(View v) { - Intent intent = new Intent("android.intent.action.MOBIADSLIST"). - setComponent(new ComponentName("de.android.mobiads", "de.android.mobiads.list.MobiAdsListActivity")); - this.startActivity(intent); + + public void onClickLocalAds(final View v) { + final Intent intent = new Intent("android.intent.action.MOBIADSLIST"). + setComponent(new ComponentName("de.android.mobiads", "de.android.mobiads.list.MobiAdsListActivity")); + this.startActivity(intent); } - private void createErrorDialog(int title) { - DialogFragment newFragment = ErrorDialogFragment.newInstance(title); + private void createErrorDialog(final int title) { + final DialogFragment newFragment = ErrorDialogFragment.newInstance(title); newFragment.show(getFragmentManager(), "errorDialog"); } - + public void doPositiveClick() { - StrictMode.setThreadPolicy(currentPolicy); - finish(); + StrictMode.setThreadPolicy(currentPolicy); + finish(); } public void doNegativeClick() { } - + public static class ErrorDialogFragment extends DialogFragment { - - public static ErrorDialogFragment newInstance(int title) { - ErrorDialogFragment frag = new ErrorDialogFragment(); - Bundle args = new Bundle(); - - args.putInt("title", title); - frag.setArguments(args); - - return frag; - } - - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - int title = getArguments().getInt("title"); - - return new AlertDialog.Builder(getActivity()) - .setIcon(android.R.drawable.ic_dialog_alert) - .setTitle(title) - .setPositiveButton(R.string.button_ok, - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - - } - } - ) - .create(); - } - } + + public static ErrorDialogFragment newInstance(final int title) { + final ErrorDialogFragment frag = new ErrorDialogFragment(); + final Bundle args = new Bundle(); + + args.putInt("title", title); + frag.setArguments(args); + + return frag; + } + + @Override + public Dialog onCreateDialog(final Bundle savedInstanceState) { + final int title = getArguments().getInt("title"); + + return new AlertDialog.Builder(getActivity()) + .setIcon(android.R.drawable.ic_dialog_alert) + .setTitle(title) + .setPositiveButton(R.string.button_ok, + new DialogInterface.OnClickListener() { + @Override + public void onClick(final DialogInterface dialog, final int whichButton) { + + } + } + ) + .create(); + } + } } diff --git a/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsService.java b/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsService.java index d18e836..8553316 100644 --- a/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsService.java +++ b/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsService.java @@ -1,6 +1,7 @@ package de.android.mobiads; import java.util.ArrayList; + import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; @@ -24,10 +25,10 @@ import de.android.mobiads.batch.MobiAdsBatch; import de.android.mobiads.list.MobiAdsLatestList; public class MobiAdsService extends Service { - private MobiAdsBatch mobiAdsBatch; - /** For showing and hiding our notification. */ + private MobiAdsBatch mobiAdsBatch; + /** For showing and hiding our notification. */ NotificationManager notificationManager; - /** + /** * Command to the service to register a client, receiving callbacks * from the service. The Message's replyTo field must be a Messenger of * the client where callbacks should be sent. @@ -47,15 +48,26 @@ public class MobiAdsService extends Service { * any registered clients with the new value. */ public static final int MSG_SET_VALUE = 3; - + private LocationManager locationManager; private LocationListener locationListener; - + private final ArrayList mClients = new ArrayList(); /** Holds last value set by a client. */ int mValue = 0; - + /** + * Meters update rate value used by LocationManager + * and the user may change it using the settings activity. + */ + private float metersUpdateRateValue = 10; + + /** + * Elapsed time between location updates. Value used by LocationManager + * and the user may change it using the settings activity. + */ + private long timeUpdateRateValue = 0; + /** * Class for clients to access. Because we know this service always * runs in the same process as its clients, we don't need to deal with @@ -68,167 +80,173 @@ public class MobiAdsService extends Service { } private final BroadcastReceiver receiver = new BroadcastReceiver() { - - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - //This will be run in the main thread of this service. It might be interesting to use a Handler - //for this receiver implementing its own thread. :/ - //TODO: If I do not want to have any trouble, to use a synchronize to access this code here and when - //receiving new ads. Besides you are using the same code xD. No time right now. I must improve my code - //but I am in a hurry. - if(action.equals("de.android.mobiads.MOBIADSSERVICERECEIVER")){ - updateNotification(); - } - } - }; - + + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + //This will be run in the main thread of this service. It might be interesting to use a Handler + //for this receiver implementing its own thread. :/ + //TODO: If I do not want to have any trouble, to use a synchronize to access this code here and when + //receiving new ads. Besides you are using the same code xD. No time right now. I must improve my code + //but I am in a hurry. + if(action.equals("de.android.mobiads.MOBIADSSERVICERECEIVER")){ + updateNotification(); + } + } + }; + @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: + public int onStartCommand(final Intent intent, final int flags, final int startId) { + final String cookie = intent.getStringExtra("cookie"); + metersUpdateRateValue = Float.parseFloat(intent.getStringExtra("meters_update_rate_value")); + timeUpdateRateValue = 60 * 1000 * Integer.parseInt(intent.getStringExtra("time_update_rate_value")); + + //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, cookie); - - Criteria criteria = new Criteria(); + this.mobiAdsBatch = new MobiAdsBatch(this.getResources().getString(R.string.user_agent_web_service), + this.getResources().getString(R.string.encoded_web_service), this, cookie); + + final Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); - criteria.setAltitudeRequired(false); + criteria.setAltitudeRequired(true); criteria.setBearingAccuracy(Criteria.NO_REQUIREMENT); criteria.setBearingRequired(false); criteria.setCostAllowed(false); criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH); criteria.setPowerRequirement(Criteria.POWER_MEDIUM); - criteria.setSpeedAccuracy(Criteria.ACCURACY_LOW); - criteria.setSpeedRequired(true); - criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT); - - + criteria.setSpeedAccuracy(Criteria.NO_REQUIREMENT); + criteria.setSpeedRequired(false); + criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH); + + // Acquire a reference to the system Location Manager this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates this.locationListener = new LocationListener() { - - public void onLocationChanged(Location location) { - // Called when a new location is found by the network location provider. - // This method is run by the main thread of this Dalvik process. - // Called when a new location is found by the network location provider. - MobiAdsService.this.mobiAdsBatch.makeUseOfNewLocation(location); + + @Override + public void onLocationChanged(final Location location) { + // Called when a new location is found by the network location provider. + // This method is run by the main thread of this Dalvik process. + // Called when a new location is found by the network location provider. + MobiAdsService.this.mobiAdsBatch.makeUseOfNewLocation(location); } - public void onStatusChanged(String provider, int status, Bundle extras) { - //1. Find out the provider state. (see Copilot.java code GPSLocationListener) - //2. If it is TEMPORARILY_UNAVAILABLE: - //2.1. locationManager.removeUpdates(locationListener); <--- Stop wasting GPS or GSM connections - //2.2. Launch Timer with TimerTask 30 or 60 seconds before to enable the locationManager to find out if the provider status changed. - //3. If OUT_OF_SERVICE - //3.1. locationManager.removeUpdates(locationListener); <--- Stop wasting GPS or GSM connections - //3.2. Launch Timer with TimerTask 30 or 60 seconds before to enable the locationManager to find out if the provider status changed. - //4. If AVAILABLE - // Nothing to do here. - //Just when we are in the second or third point we have to stop draining battery because it is useless. - + @Override + public void onStatusChanged(final String provider, final int status, final Bundle extras) { + //1. Find out the provider state. (see Copilot.java code GPSLocationListener) + //2. If it is TEMPORARILY_UNAVAILABLE: + //2.1. locationManager.removeUpdates(locationListener); <--- Stop wasting GPS or GSM connections + //2.2. Launch Timer with TimerTask 30 or 60 seconds before to enable the locationManager to find out if the provider status changed. + //3. If OUT_OF_SERVICE + //3.1. locationManager.removeUpdates(locationListener); <--- Stop wasting GPS or GSM connections + //3.2. Launch Timer with TimerTask 30 or 60 seconds before to enable the locationManager to find out if the provider status changed. + //4. If AVAILABLE + // Nothing to do here. + //Just when we are in the second or third point we have to stop draining battery because it is useless. + } - public void onProviderEnabled(String provider) {} + @Override + public void onProviderEnabled(final String provider) {} - public void onProviderDisabled(String provider) {} - }; + @Override + public void onProviderDisabled(final String provider) {} + }; // Register the listener with the Location Manager to receive location updates - locationManager.requestLocationUpdates(0, 10, criteria, locationListener, null); - + locationManager.requestLocationUpdates(timeUpdateRateValue, metersUpdateRateValue, criteria, locationListener, null); + notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); - - + + updateNotification (); - - - IntentFilter filter = new IntentFilter(); + + + final IntentFilter filter = new IntentFilter(); filter.addAction("de.android.mobiads.MOBIADSSERVICERECEIVER"); registerReceiver(receiver, filter); - + return Service.START_REDELIVER_INTENT; } - - @Override - public IBinder onBind(Intent intent) { - return mMessenger.getBinder(); - } - - - @Override + + @Override + public IBinder onBind(final Intent intent) { + return mMessenger.getBinder(); + } + + + @Override public void onDestroy() { - unregisterReceiver(receiver); + unregisterReceiver(receiver); // Cancel the persistent notification. - notificationManager.cancel(R.string.remote_service_title_notification); - + notificationManager.cancel(R.string.remote_service_title_notification); + if (this.locationListener != null) { - this.locationManager.removeUpdates(this.locationListener); + this.locationManager.removeUpdates(this.locationListener); } - + if (this.mobiAdsBatch != null) { - this.mobiAdsBatch.endBatch(); + this.mobiAdsBatch.endBatch(); } } - - - public void updateNotification () { - - int noReadCount = 0; + + + public void updateNotification () { + + int noReadCount = 0; CharSequence contentText; if ((noReadCount = this.mobiAdsBatch.noReadAdsCount()) == 0) { - contentText = getText(R.string.remote_service_content_empty_notification); - showNotification(0, noReadCount, contentText, null); + contentText = getText(R.string.remote_service_content_empty_notification); + showNotification(0, noReadCount, contentText, null); } else { - contentText = getText(R.string.remote_service_content_notification); - showNotification(0, noReadCount, contentText, MobiAdsLatestList.class); + contentText = getText(R.string.remote_service_content_notification); + showNotification(0, noReadCount, contentText, MobiAdsLatestList.class); } } - /** + /** * Show a notification while this service is running. */ - private void showNotification(final int level, final int noReadAds, CharSequence contentText, Class cls) { - PendingIntent contentIntent = null; - - if (cls != null) { - Intent intent = new Intent(this, cls); + private void showNotification(final int level, final int noReadAds, final CharSequence contentText, final Class cls) { + PendingIntent contentIntent = null; + + if (cls != null) { + final Intent intent = new Intent(this, cls); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // The PendingIntent to launch our activity if the user selects this notification contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); - } - - + } + + // Set the icon, scrolling text and timestamp - Notification.Builder notificationBuilder = new Notification.Builder(getApplicationContext()). - setSmallIcon(R.drawable.wheelnotification, level). - setTicker(getText(R.string.remote_service_started_notification)). - setWhen(System.currentTimeMillis()). - setContentText(contentText). - setContentTitle(getText(R.string.remote_service_title_notification)). - setNumber(noReadAds). - setContentIntent(contentIntent); - Notification notification = notificationBuilder.getNotification(); + final Notification.Builder notificationBuilder = new Notification.Builder(getApplicationContext()). + setSmallIcon(R.drawable.wheelnotification, level). + setTicker(getText(R.string.remote_service_started_notification)). + setWhen(System.currentTimeMillis()). + setContentText(contentText). + setContentTitle(getText(R.string.remote_service_title_notification)). + setNumber(noReadAds). + setContentIntent(contentIntent); + final Notification notification = notificationBuilder.getNotification(); notification.flags |= Notification.FLAG_NO_CLEAR; // Send the notification. // We use a string id because it is a unique number. We use it later to cancel. notificationManager.notify(R.string.remote_service_title_notification, notification); } - + /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override - public void handleMessage(Message msg) { + public void handleMessage(final Message msg) { switch (msg.what) { case MSG_REGISTER_CLIENT: mClients.add(msg.replyTo); @@ -242,7 +260,7 @@ public class MobiAdsService extends Service { try { mClients.get(i).send(Message.obtain(null, MSG_SET_VALUE, mValue, 0)); - } catch (RemoteException e) { + } catch (final RemoteException e) { // The client is dead. Remove it from the list; // we are going through the list from back to front // so this is safe to do inside the loop. @@ -258,5 +276,5 @@ public class MobiAdsService extends Service { final Messenger mMessenger = new Messenger(new IncomingHandler()); - + } diff --git a/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsSettings.java b/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsSettings.java index c038c82..18bd3c9 100644 --- a/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsSettings.java +++ b/Android/MobiAdsReloaded/src/de/android/mobiads/MobiAdsSettings.java @@ -16,6 +16,7 @@ import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.preference.CheckBoxPreference; +import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.widget.TextView; @@ -24,191 +25,197 @@ import de.android.mobiads.list.MobiAdsList; public class MobiAdsSettings extends Activity { - @Override - protected void onCreate(Bundle savedInstanceState) { + @Override + protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); - FragmentManager fm = getFragmentManager(); + final FragmentManager fm = getFragmentManager(); // Create the list fragment and add it as our sole content. if (fm.findFragmentById(android.R.id.content) == null) { - MobiAdsSettingsFragment list = new MobiAdsSettingsFragment(); + final MobiAdsSettingsFragment list = new MobiAdsSettingsFragment(); fm.beginTransaction().add(android.R.id.content, list).commit(); } - - + + + } + + public static class MobiAdsSettingsFragment extends PreferenceFragment { + + @Override + public void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Load the preferences from an XML resource + addPreferencesFromResource(R.xml.preferences); + } + + @Override + public void onActivityCreated(final Bundle savedInstanceState) { + super.onActivityCreated(savedInstanceState); + + final CheckBoxPreference checkBoxPreference = (CheckBoxPreference) findPreference("service_started"); + checkBoxPreference.setChecked(isMyServiceRunning()); + checkBoxPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + + @Override + public boolean onPreferenceClick(final Preference preference) { + final CheckBoxPreference checkBoxPreference = (CheckBoxPreference) preference; + if (checkBoxPreference.isChecked()) { + if (Cookie.getCookie() != null) { + final Intent intent = new Intent(getActivity(), MobiAdsService.class); + final ListPreference metersUpdateRate = (ListPreference) findPreference("meters_update_rate"); + final ListPreference timeUpdateRate = (ListPreference) findPreference("time_update_rate"); + intent.putExtra("cookie", Cookie.getCookie()); + intent.putExtra("meters_update_rate_value", metersUpdateRate.getValue()); + intent.putExtra("time_update_rate_value", timeUpdateRate.getValue()); + //((MobiAdsSettings)getActivity()).doBindService(); + getActivity().startService(intent); + } + else { + final DialogFragment newFragment = MobiAdsList.AlertDialogFragment.newInstance(R.string.alert_dialog_not_logged); + newFragment.show(getFragmentManager(), "alertDialog"); + checkBoxPreference.setChecked(false); + } + } + else { + //((MobiAdsSettings)getActivity()).doUnbindService(); + getActivity().stopService(new Intent(getActivity(), MobiAdsService.class)); + } + return false; + } + }); + } + + private boolean isMyServiceRunning() { + final ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); + for (final RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (MobiAdsService.class.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; + } + } + + + + + + + + + /** 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; + + /** + * Handler of incoming messages from service. + */ + class IncomingHandler extends Handler { + @Override + public void handleMessage(final Message msg) { + switch (msg.what) { + case MobiAdsService.MSG_SET_VALUE: + mCallbackText.setText("Received from service: " + msg.arg1); + break; + default: + super.handleMessage(msg); + } + } + } + + /** + * Target we publish for clients to send messages to IncomingHandler. + */ + final Messenger mMessenger = new Messenger(new IncomingHandler()); + + /** + * Class for interacting with the main interface of the service. + */ + private final ServiceConnection mConnection = new ServiceConnection() { + + @Override + public void onServiceConnected(final ComponentName className, + final IBinder service) { + // This is called when the connection with the service has been + // established, giving us the service object we can use to + // interact with the service. We are communicating with our + // 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. + try { + Message msg = Message.obtain(null, + MobiAdsService.MSG_REGISTER_CLIENT); + msg.replyTo = mMessenger; + mService.send(msg); + + // Give it some value as an example. + msg = Message.obtain(null, + MobiAdsService.MSG_SET_VALUE, this.hashCode(), 0); + mService.send(msg); + } catch (final RemoteException e) { + // In this case the service has crashed before we could even + // do anything with it; we can count on soon being + // 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(MobiAdsSettings.this, R.string.button_messagebind, + Toast.LENGTH_SHORT).show(); + } + + @Override + public void onServiceDisconnected(final 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(MobiAdsSettings.this, R.string.button_messageunbind, + Toast.LENGTH_SHORT).show(); + } + }; + + private void doBindService() { + // Establish a connection with the service. We use an explicit + // class name because there is no reason to be able to let other + // applications replace our component. + bindService(new Intent(this, + MobiAdsService.class), mConnection, Context.BIND_AUTO_CREATE); + mIsBound = true; + mCallbackText.setText("Binding."); + } + + private void doUnbindService() { + if (mIsBound) { + // If we have received the service, and hence registered with + // it, then now is the time to unregister. + if (mService != null) { + try { + final Message msg = Message.obtain(null, + MobiAdsService.MSG_UNREGISTER_CLIENT); + msg.replyTo = mMessenger; + mService.send(msg); + } catch (final RemoteException e) { + // There is nothing special we need to do if the service + // has crashed. + } + } + + // Detach our existing connection. + unbindService(mConnection); + mIsBound = false; + mCallbackText.setText("Unbinding."); + } } - - public static class MobiAdsSettingsFragment extends PreferenceFragment { - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - // Load the preferences from an XML resource - addPreferencesFromResource(R.xml.preferences); - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - - CheckBoxPreference checkBoxPreference = (CheckBoxPreference) findPreference("service_started"); - checkBoxPreference.setChecked(isMyServiceRunning()); - checkBoxPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - - @Override - public boolean onPreferenceClick(Preference preference) { - CheckBoxPreference checkBoxPreference = (CheckBoxPreference) preference; - if (checkBoxPreference.isChecked()) { - if (Cookie.getCookie() != null) { - Intent intent = new Intent(getActivity(), MobiAdsService.class); - intent.putExtra("cookie", Cookie.getCookie()); - //((MobiAdsSettings)getActivity()).doBindService(); - getActivity().startService(intent); - } - else { - DialogFragment newFragment = MobiAdsList.AlertDialogFragment.newInstance(R.string.alert_dialog_not_logged); - newFragment.show(getFragmentManager(), "alertDialog"); - checkBoxPreference.setChecked(false); - } - } - else { - //((MobiAdsSettings)getActivity()).doUnbindService(); - getActivity().stopService(new Intent(getActivity(), MobiAdsService.class)); - } - return false; - } - }); - } - - private boolean isMyServiceRunning() { - ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); - for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { - if (MobiAdsService.class.getName().equals(service.service.getClassName())) { - return true; - } - } - return false; - } - } - - - - - - - - - /** 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; - - /** - * Handler of incoming messages from service. - */ - class IncomingHandler extends Handler { - @Override - 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); - } - } - } - - /** - * Target we publish for clients to send messages to IncomingHandler. - */ - final Messenger mMessenger = new Messenger(new IncomingHandler()); - - /** - * Class for interacting with the main interface of the service. - */ - private ServiceConnection mConnection = new ServiceConnection() { - - public void onServiceConnected(ComponentName className, - IBinder service) { - // This is called when the connection with the service has been - // established, giving us the service object we can use to - // interact with the service. We are communicating with our - // 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. - try { - Message msg = Message.obtain(null, - MobiAdsService.MSG_REGISTER_CLIENT); - msg.replyTo = mMessenger; - mService.send(msg); - - // Give it some value as an example. - msg = Message.obtain(null, - MobiAdsService.MSG_SET_VALUE, this.hashCode(), 0); - mService.send(msg); - } catch (RemoteException e) { - // In this case the service has crashed before we could even - // do anything with it; we can count on soon being - // 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(MobiAdsSettings.this, R.string.button_messagebind, - 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(MobiAdsSettings.this, R.string.button_messageunbind, - Toast.LENGTH_SHORT).show(); - } - }; - - private void doBindService() { - // Establish a connection with the service. We use an explicit - // class name because there is no reason to be able to let other - // applications replace our component. - bindService(new Intent(this, - MobiAdsService.class), mConnection, Context.BIND_AUTO_CREATE); - mIsBound = true; - mCallbackText.setText("Binding."); - } - - private void doUnbindService() { - if (mIsBound) { - // If we have received the service, and hence registered with - // it, then now is the time to unregister. - if (mService != null) { - try { - Message msg = Message.obtain(null, - MobiAdsService.MSG_UNREGISTER_CLIENT); - msg.replyTo = mMessenger; - mService.send(msg); - } catch (RemoteException e) { - // There is nothing special we need to do if the service - // has crashed. - } - } - - // Detach our existing connection. - unbindService(mConnection); - mIsBound = false; - mCallbackText.setText("Unbinding."); - } - } } diff --git a/Android/MobiAdsReloaded/src/de/android/mobiads/batch/MobiAdsBatch.java b/Android/MobiAdsReloaded/src/de/android/mobiads/batch/MobiAdsBatch.java index 72d409c..aeb8a75 100644 --- a/Android/MobiAdsReloaded/src/de/android/mobiads/batch/MobiAdsBatch.java +++ b/Android/MobiAdsReloaded/src/de/android/mobiads/batch/MobiAdsBatch.java @@ -35,6 +35,7 @@ import android.net.Uri; import android.net.http.AndroidHttpClient; import android.util.Log; import de.android.mobiads.MobiAdsService; +import de.android.mobiads.R; import de.android.mobiads.provider.Indexer; public class MobiAdsBatch { @@ -63,7 +64,7 @@ public class MobiAdsBatch { final String longitude = String.valueOf(location.getLongitude()); final String latitudeReplace = latitude.replace(".", ","); final String longitudeReplace = longitude.replace(".", ","); - final String URLAuth = "http://users.mobiads.gumartinm.name/userfront.php/api/" + latitudeReplace + "/" + longitudeReplace + "/gpsads.json"; + final String URLAuth = this.context.getResources().getString(R.string.url_api_web_services) + latitudeReplace + "/" + longitudeReplace + "/gpsads.json"; URL url = null; try { @@ -218,7 +219,7 @@ public class MobiAdsBatch { public void downloadImage(final String image, final String path) throws MalformedURLException, URISyntaxException, FileNotFoundException, IOException { final HttpGet httpGet = new HttpGet(); - final String URLAd = USERS_SERVER + image; + final String URLAd = MobiAdsBatch.this.context.getResources().getString(R.string.url_images) + image; HttpResponse httpResponse = null; URL url = null; diff --git a/Android/MobiAdsReloaded/src/de/android/mobiads/list/MobiAdsLatestList.java b/Android/MobiAdsReloaded/src/de/android/mobiads/list/MobiAdsLatestList.java index 3d77300..41455a9 100644 --- a/Android/MobiAdsReloaded/src/de/android/mobiads/list/MobiAdsLatestList.java +++ b/Android/MobiAdsReloaded/src/de/android/mobiads/list/MobiAdsLatestList.java @@ -5,6 +5,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; + import android.app.ListActivity; import android.app.LoaderManager; import android.content.AsyncTaskLoader; @@ -33,294 +34,294 @@ import de.android.mobiads.R; import de.android.mobiads.provider.Indexer; public class MobiAdsLatestList extends ListActivity implements LoaderManager.LoaderCallbacks> { - AdsEntryLatestAdapter mAdapter; - private BroadcastReceiver mReceiver; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - mReceiver = new BroadcastReceiver() { - - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - //This will be run in the main thread of this service. It might be interesting to use a Handler - //for this receiver implementing its own thread. :/ - if(action.equals("de.android.mobiads.MOBIADSLISTRECEIVER")){ - getLoaderManager().restartLoader(0, null, MobiAdsLatestList.this); - } - } - }; - - IntentFilter filter = new IntentFilter(); + AdsEntryLatestAdapter mAdapter; + private BroadcastReceiver mReceiver; + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mReceiver = new BroadcastReceiver() { + + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + //This will be run in the main thread of this service. It might be interesting to use a Handler + //for this receiver implementing its own thread. :/ + if(action.equals("de.android.mobiads.MOBIADSLISTRECEIVER")){ + getLoaderManager().restartLoader(0, null, MobiAdsLatestList.this); + } + } + }; + + final IntentFilter filter = new IntentFilter(); filter.addAction("de.android.mobiads.MOBIADSLISTRECEIVER"); registerReceiver(mReceiver, filter); - } - - @Override + } + + @Override protected void onResume() { - super.onResume(); - - mAdapter = new AdsEntryLatestAdapter(this, R.layout.ads_entry_list_item); - setListAdapter(mAdapter); - - getListView().setTextFilterEnabled(true); - - // Tell the list view to show one checked/activated item at a time. - getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); - - getListView().setOnItemClickListener(new OnItemClickListener() { - - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - final AdsEntry entry = mAdapter.getItem(position); - - if (!entry.isRead()) { - setIsReadEntry(entry); - } - - //Change notification (if there is one) - Intent updateDatabase = new Intent("de.android.mobiads.MOBIADSSERVICERECEIVER"); - sendBroadcast(updateDatabase); - - mAdapter.remove(entry); - //Update view lists - updateDatabase = new Intent("de.android.mobiads.MOBIADSLISTRECEIVER"); - sendBroadcast(updateDatabase); - - Uri uri = Uri.parse(mAdapter.getItem(position).getURL()); - startActivity(new Intent(Intent.ACTION_VIEW, uri)); - - mAdapter.notifyDataSetChanged(); - } - }); - - registerForContextMenu(getListView()); - - getLoaderManager().initLoader(0, null, this); - } - - @Override - protected void onDestroy() { - unregisterReceiver(mReceiver); - super.onDestroy(); - } - - @Override - public Loader> onCreateLoader(int id, Bundle args) { - // This is called when a new Loader needs to be created. This - // sample only has one Loader with no arguments, so it is simple. - return new AdsListLoader(this); - } - - @Override - public void onLoadFinished(Loader> loader, - List data) { - - mAdapter.setData(data); - mAdapter.notifyDataSetChanged(); - } - - @Override - public void onLoaderReset(Loader> loader) { - mAdapter.setData(null); - } - - @Override - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + super.onResume(); + + mAdapter = new AdsEntryLatestAdapter(this, R.layout.ads_entry_list_item); + setListAdapter(mAdapter); + + getListView().setTextFilterEnabled(true); + + // Tell the list view to show one checked/activated item at a time. + getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); + + getListView().setOnItemClickListener(new OnItemClickListener() { + + @Override + public void onItemClick(final AdapterView parent, final View view, final int position, final long id) { + final AdsEntry entry = mAdapter.getItem(position); + + if (!entry.isRead()) { + setIsReadEntry(entry); + } + + //Change notification (if there is one) + Intent updateDatabase = new Intent("de.android.mobiads.MOBIADSSERVICERECEIVER"); + sendBroadcast(updateDatabase); + + final Uri uri = Uri.parse(mAdapter.getItem(position).getURL()); + mAdapter.remove(entry); + //Update view lists + updateDatabase = new Intent("de.android.mobiads.MOBIADSLISTRECEIVER"); + sendBroadcast(updateDatabase); + + startActivity(new Intent(Intent.ACTION_VIEW, uri)); + + mAdapter.notifyDataSetChanged(); + } + }); + + registerForContextMenu(getListView()); + + getLoaderManager().initLoader(0, null, this); + } + + @Override + protected void onDestroy() { + unregisterReceiver(mReceiver); + super.onDestroy(); + } + + @Override + public Loader> onCreateLoader(final int id, final Bundle args) { + // This is called when a new Loader needs to be created. This + // sample only has one Loader with no arguments, so it is simple. + return new AdsListLoader(this); + } + + @Override + public void onLoadFinished(final Loader> loader, + final List data) { + + mAdapter.setData(data); + mAdapter.notifyDataSetChanged(); + } + + @Override + public void onLoaderReset(final Loader> loader) { + mAdapter.setData(null); + } + + @Override + public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); - MenuInflater inflater = getMenuInflater(); + final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.selectedmenuads, menu); } - - - @Override - public boolean onContextItemSelected(final MenuItem item) { - final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); - - switch (item.getItemId()) { - case R.id.selectedmenu_remove: - removeAd(info.position); - return true; - default: - return super.onContextItemSelected(item); - } - } - - public void removeAd(int position){ - final AdsEntry entry = mAdapter.getItem(position); - int idAd = entry.getIdAd(); - final Uri uriDelete = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer" - + "/idad/" + idAd); - - getContentResolver().delete(uriDelete, null, null); - - //Change notification (if there is one) - Intent updateDatabase = new Intent("de.android.mobiads.MOBIADSSERVICERECEIVER"); - sendBroadcast(updateDatabase); - - //Update view lists - updateDatabase = new Intent("de.android.mobiads.MOBIADSLISTRECEIVER"); - sendBroadcast(updateDatabase); - - mAdapter.remove(entry); - - mAdapter.notifyDataSetChanged(); - } - - - private void setIsReadEntry(final AdsEntry entry) { - final Uri uriUpdate = Uri.parse("content://" + "de.android.mobiads.provider" + - "/" + "indexer/idad/" + entry.getIdAd()); - final ContentValues values = new ContentValues(); - - values.put(Indexer.Index.COLUMN_NAME_IS_READ, new Integer(1)); - - getContentResolver().update(uriUpdate, values, null, null); - - entry.setIsRead(true); - } - - - /** - * A custom Loader that loads all of the installed applications. - */ - public static class AdsListLoader extends AsyncTaskLoader> { - private static final String TAG = "AdsListLoader"; - List mApps; - - public AdsListLoader(Context context) { - super(context); - } - - /** - * This is where the bulk of our work is done. This function is - * called in a background thread and should generate a new set of - * data to be published by the loader. - */ - @Override - public List loadInBackground() { - // Create corresponding array of entries and load their labels. - List entries = getAdsEntries(); - - return entries; - } - - private List getAdsEntries() { - final List entries = new ArrayList(); - final Uri uri = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer" + "/isRead/"); - final ContentValues values = new ContentValues(); - - Cursor cursor = getContext().getContentResolver().query(uri, null, null, null, null); - try { - if (cursor.moveToFirst()) { - do { - values.clear(); - Bitmap bitMap = null; - FileInputStream file = null; - try { - file = getContext().openFileInput(cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_PATH))); - bitMap = BitmapFactory.decodeStream(file); - } catch (FileNotFoundException e) { - //Giving more chances to other ads - continue; - } catch (IllegalArgumentException e) { - //Giving more chances to other ads - continue; - } - finally { - if (file != null) { - try { - file.close(); - } catch (IOException e) { - Log.w(TAG, "Error while closing image file."); - } - } - } - - boolean readStatus; - if ( cursor.getInt(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_IS_READ)) == 0) { - readStatus = false; - } - else { - readStatus = true; - } - - entries.add(new AdsEntry(cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_AD_NAME)), - cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_TEXT)), bitMap, - cursor.getInt(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_ID_AD)), - cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_URL)), - readStatus)); - }while (cursor.moveToNext()); - } - }finally { - cursor.close(); - } - - return entries; - } - - /** - * Called when there is new data to deliver to the client. The - * super class will take care of delivering it; the implementation - * here just adds a little more logic. - */ - @Override - public void deliverResult(List apps) { - mApps = apps; - - if (isStarted()) { - // If the Loader is currently started, we can immediately - // deliver its results. - super.deliverResult(apps); - } - } - - /** - * Handles a request to start the Loader. - */ - @Override - protected void onStartLoading() { - if (mApps != null) { - // If we currently have a result available, deliver it - // immediately. - deliverResult(mApps); - } - - if (takeContentChanged() || mApps == null) { - // If the data has changed since the last time it was loaded - // or is not currently available, start a load. - forceLoad(); - } - } - - /** - * Handles a request to cancel a load. - */ - @Override - public void onCanceled(List apps) { - super.onCanceled(apps); - - // At this point we can release the resources associated with 'apps' - // if needed. - } - - /** - * Handles a request to completely reset the Loader. - */ - @Override - protected void onReset() { - super.onReset(); - - // Ensure the loader is stopped - onStopLoading(); - - // At this point we can release the resources associated with 'apps' - // if needed. - if (mApps != null) { - mApps = null; - } - } - } + + + @Override + public boolean onContextItemSelected(final MenuItem item) { + final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); + + switch (item.getItemId()) { + case R.id.selectedmenu_remove: + removeAd(info.position); + return true; + default: + return super.onContextItemSelected(item); + } + } + + public void removeAd(final int position){ + final AdsEntry entry = mAdapter.getItem(position); + final int idAd = entry.getIdAd(); + final Uri uriDelete = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer" + + "/idad/" + idAd); + + getContentResolver().delete(uriDelete, null, null); + + //Change notification (if there is one) + Intent updateDatabase = new Intent("de.android.mobiads.MOBIADSSERVICERECEIVER"); + sendBroadcast(updateDatabase); + + //Update view lists + updateDatabase = new Intent("de.android.mobiads.MOBIADSLISTRECEIVER"); + sendBroadcast(updateDatabase); + + mAdapter.remove(entry); + + mAdapter.notifyDataSetChanged(); + } + + + private void setIsReadEntry(final AdsEntry entry) { + final Uri uriUpdate = Uri.parse("content://" + "de.android.mobiads.provider" + + "/" + "indexer/idad/" + entry.getIdAd()); + final ContentValues values = new ContentValues(); + + values.put(Indexer.Index.COLUMN_NAME_IS_READ, new Integer(1)); + + getContentResolver().update(uriUpdate, values, null, null); + + entry.setIsRead(true); + } + + + /** + * A custom Loader that loads all of the installed applications. + */ + public static class AdsListLoader extends AsyncTaskLoader> { + private static final String TAG = "AdsListLoader"; + List mApps; + + public AdsListLoader(final Context context) { + super(context); + } + + /** + * This is where the bulk of our work is done. This function is + * called in a background thread and should generate a new set of + * data to be published by the loader. + */ + @Override + public List loadInBackground() { + // Create corresponding array of entries and load their labels. + final List entries = getAdsEntries(); + + return entries; + } + + private List getAdsEntries() { + final List entries = new ArrayList(); + final Uri uri = Uri.parse("content://" + "de.android.mobiads.provider" + "/" + "indexer" + "/isRead/"); + final ContentValues values = new ContentValues(); + + final Cursor cursor = getContext().getContentResolver().query(uri, null, null, null, null); + try { + if (cursor.moveToFirst()) { + do { + values.clear(); + Bitmap bitMap = null; + FileInputStream file = null; + try { + file = getContext().openFileInput(cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_PATH))); + bitMap = BitmapFactory.decodeStream(file); + } catch (final FileNotFoundException e) { + //Giving more chances to other ads + continue; + } catch (final IllegalArgumentException e) { + //Giving more chances to other ads + continue; + } + finally { + if (file != null) { + try { + file.close(); + } catch (final IOException e) { + Log.w(TAG, "Error while closing image file."); + } + } + } + + boolean readStatus; + if ( cursor.getInt(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_IS_READ)) == 0) { + readStatus = false; + } + else { + readStatus = true; + } + + entries.add(new AdsEntry(cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_AD_NAME)), + cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_TEXT)), bitMap, + cursor.getInt(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_ID_AD)), + cursor.getString(cursor.getColumnIndexOrThrow(Indexer.Index.COLUMN_NAME_URL)), + readStatus)); + }while (cursor.moveToNext()); + } + }finally { + cursor.close(); + } + + return entries; + } + + /** + * Called when there is new data to deliver to the client. The + * super class will take care of delivering it; the implementation + * here just adds a little more logic. + */ + @Override + public void deliverResult(final List apps) { + mApps = apps; + + if (isStarted()) { + // If the Loader is currently started, we can immediately + // deliver its results. + super.deliverResult(apps); + } + } + + /** + * Handles a request to start the Loader. + */ + @Override + protected void onStartLoading() { + if (mApps != null) { + // If we currently have a result available, deliver it + // immediately. + deliverResult(mApps); + } + + if (takeContentChanged() || mApps == null) { + // If the data has changed since the last time it was loaded + // or is not currently available, start a load. + forceLoad(); + } + } + + /** + * Handles a request to cancel a load. + */ + @Override + public void onCanceled(final List apps) { + super.onCanceled(apps); + + // At this point we can release the resources associated with 'apps' + // if needed. + } + + /** + * Handles a request to completely reset the Loader. + */ + @Override + protected void onReset() { + super.onReset(); + + // Ensure the loader is stopped + onStopLoading(); + + // At this point we can release the resources associated with 'apps' + // if needed. + if (mApps != null) { + mApps = null; + } + } + } }