Search code examples
androidserviceandroid-servicealarmmanagerandroid-alarms

Android: Alarm not starting service


Requirement: Start background service repeatedly

Design: Using AlarmManager

What I did:

<service
    android:name=".MyService"
    android:exported="false" >
</service>

AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), SERVICE_ALARM_INTERVAL, pendingIntent);

The service class is straight forward extends Service with:

@Override
public void onCreate() {              
    HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    //Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
    mContext = getApplicationContext();
    Toast.makeText(mContext, "Service!!!!!", Toast.LENGTH_LONG).show();
    Log.e("tag", "Service!!!");
}

Problem: The Toast message and the Log printing not executed.

What I did wrong here?

Thanks,


Solution

  • You are using PendingIntent.getBroadcast() - this triggers a broadcast. You need to use PendingIntent.getService() if you want to trigger a service.