Mainly indentation changes... That sucks, but I have not time to sort indentation changes from the real ones...
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 {
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;
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;
#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
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string-array name="meters_update_rate_value">
+ <item>10</item>
+ <item>20</item>
+ <item>30</item>
+ <item>40</item>
+ <item>50</item>
+ </string-array>
+ <string-array name="meters_update_rate_human_value">
+ <item>10 meters</item>
+ <item>20 meters</item>
+ <item>30 meters</item>
+ <item>40 meters</item>
+ <item>50 meters</item>
+ </string-array>
+ <string-array name="time_update_rate_value">
+ <item>0</item>
+ <item>1</item>
+ <item>2</item>
+ <item>5</item>
+ <item>10</item>
+ <item>20</item>
+ </string-array>
+ <string-array name="time_update_rate_human_value">
+ <item>0 minutes</item>
+ <item>1 minute</item>
+ <item>2 minutes</item>
+ <item>5 minutes</item>
+ <item>10 minutes</item>
+ <item>20 minutes</item>
+ </string-array>
+</resources>
\ No newline at end of file
<string name="remote_service_stopped_notification">MobiAds Service Stopped</string>
<string name="remote_service_title_notification">MobiAds Service</string>
<string name="url_login_web_service">http://users.mobiads.gumartinm.name/userfront.php/api/login/auth.json</string>
+ <string name="url_api_web_services">http://users.mobiads.gumartinm.name/userfront.php/api/</string>
+ <string name="url_images">http://companies.mobiads.gumartinm.name/uploads/images/</string>
<string name="url_web">users.mobiads.gumartinm.name</string>
<string name="user_agent_web_service">MobiAds/1.0</string>
<string name="encoded_web_service">UTF-8</string>
<string name="menuads_settings">Settings</string>
<string name="menuads_login">Login</string>
<string name="error_dialog_no_local_ads">You have no downloaded ads.</string>
+ <string name="service_preference_title">Service started</string>
+ <string name="service_preference_title_summary">Start or stop downloading ads.</string>
+ <string name="meters_update_rate_preference_title">Meters update rate</string>
+ <string name="meters_update_rate_preference_summary">Control the frequency of location updates. Lower values increase power consumption.</string>
+ <string name="time_update_rate_preference_title">Time update rate</string>
+ <string name="time_update_rate_preference_summary">Elapsed time between location updates. Lower values increase power consumption.</string>
</resources>
\ No newline at end of file
<CheckBoxPreference
android:key="service_started"
- android:title="Service started"
+ android:title="@string/service_preference_title"
+ android:summary="@string/service_preference_title_summary"
android:enabled="true"
android:selectable="true"/>
+ <ListPreference
+ android:key="meters_update_rate"
+ android:dialogTitle="@string/meters_update_rate_preference_title"
+ android:title="@string/meters_update_rate_preference_title"
+ android:summary="@string/meters_update_rate_preference_summary"
+ android:enabled="true"
+ android:selectable="true"
+ android:persistent="true"
+ android:entries="@array/meters_update_rate_human_value"
+ android:entryValues="@array/meters_update_rate_value"
+ android:defaultValue="10"/>
+ <ListPreference
+ android:key="time_update_rate"
+ android:dialogTitle="@string/time_update_rate_preference_title"
+ android:title="@string/time_update_rate_preference_title"
+ android:summary="@string/time_update_rate_preference_summary"
+ android:enabled="true"
+ android:selectable="true"
+ android:persistent="true"
+ android:entries="@array/time_update_rate_human_value"
+ android:entryValues="@array/time_update_rate_value"
+ android:defaultValue="0"/>
</PreferenceScreen>
\ No newline at end of file
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<NameValuePair> formParams = new ArrayList<NameValuePair>(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<NameValuePair> formParams = new ArrayList<NameValuePair>(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();
+ }
+ }
}
package de.android.mobiads;
import java.util.ArrayList;
+
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
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.
* any registered clients with the new value.
*/
public static final int MSG_SET_VALUE = 3;
-
+
private LocationManager locationManager;
private LocationListener locationListener;
-
+
private final ArrayList<Messenger> mClients = new ArrayList<Messenger>();
/** 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
}
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);
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.
final Messenger mMessenger = new Messenger(new IncomingHandler());
-
+
}
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;
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.");
- }
- }
}
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 {
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 {
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;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+
import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.AsyncTaskLoader;
import de.android.mobiads.provider.Indexer;
public class MobiAdsLatestList extends ListActivity implements LoaderManager.LoaderCallbacks<List<AdsEntry>> {
- 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<List<AdsEntry>> 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<List<AdsEntry>> loader,
- List<AdsEntry> data) {
-
- mAdapter.setData(data);
- mAdapter.notifyDataSetChanged();
- }
-
- @Override
- public void onLoaderReset(Loader<List<AdsEntry>> 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<List<AdsEntry>> 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<List<AdsEntry>> loader,
+ final List<AdsEntry> data) {
+
+ mAdapter.setData(data);
+ mAdapter.notifyDataSetChanged();
+ }
+
+ @Override
+ public void onLoaderReset(final Loader<List<AdsEntry>> 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<List<AdsEntry>> {
- private static final String TAG = "AdsListLoader";
- List<AdsEntry> 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<AdsEntry> loadInBackground() {
- // Create corresponding array of entries and load their labels.
- List<AdsEntry> entries = getAdsEntries();
-
- return entries;
- }
-
- private List<AdsEntry> getAdsEntries() {
- final List<AdsEntry> entries = new ArrayList<AdsEntry>();
- 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<AdsEntry> 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<AdsEntry> 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<List<AdsEntry>> {
+ private static final String TAG = "AdsListLoader";
+ List<AdsEntry> 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<AdsEntry> loadInBackground() {
+ // Create corresponding array of entries and load their labels.
+ final List<AdsEntry> entries = getAdsEntries();
+
+ return entries;
+ }
+
+ private List<AdsEntry> getAdsEntries() {
+ final List<AdsEntry> entries = new ArrayList<AdsEntry>();
+ 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<AdsEntry> 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<AdsEntry> 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;
+ }
+ }
+ }
}