You need to use AlarmManager to activate the pending intent (via the broadcast receiver) to start the background service.
Sample code for you
In your main business
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent notifyintent = new Intent(this, OnAlarmReceiver.class); notifyintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); notifyintent.setAction("android.intent.action.NOTIFY"); PendingIntent notifysender = PendingIntent.getBroadcast(this, 0, notifyintent, PendingIntent.FLAG_UPDATE_CURRENT); am.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 20 * 1000, notifysender);
Class AlarmReceiver
public class OnAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
BroadcastReceiver
private static final String NAME = "com.commonsware.cwac.wakeful.WakefulIntentService"; private static volatile PowerManager.WakeLock lockStatic = null; private static PowerManager.WakeLock lock;
Background service. Here you will notice 2 important points.
- WakeLock to make sure your device wakes up and uses the network in the background
- Hacking for LocationManager to work. I had to debug this for about 2 weeks, believe me, you need it. requestLocationUpdates and getLastKnownLocation simply will not indicate your location whenever you want. Hence AlarmManager (which works much better than Java TimerTask).
All this works in the production application in the game store.
public class UpdateCustomerRequests extends IntentService implements LocationListener { private static Context mainContext; public UpdateCustomerRequests() { super("UpdateCustomerRequests"); mHandler = new Handler(); me = this; } public static UpdateCustomerRequests getService() { if (me == null) me = new UpdateCustomerRequests(); return me; } @Override final protected void onHandleIntent(Intent intent) { mainContext = getApplicationContext(); Location myLocation; if (HomeScreen.getLocationManager() != null) {
Finally, do not forget your obvious thing.
<service android:name="com.taxeeta.UpdateCustomerRequests" android:enabled="true" android:label="@string/app_name" android:screenOrientation="portrait" android:theme="@android:style/Theme.Light.NoTitleBar" /> <receiver android:name="com.taxeeta.support.OnAlarmReceiver" android:exported="true" > <intent-filter> <action android:name="android.intent.action.NOTIFY" /> </intent-filter> </receiver> <receiver android:name="com.taxeeta.HomeScreen$ResponseReceiver" android:exported="true" > <intent-filter> <action android:name="com.taxeeta.intent.action.GET_SCREEN_UPDATES" /> </intent-filter> </receiver>
Siddharth
source share