Question

I am trying to start a service (NotificationService.java) using an alarm manager in my main activity (Home.java). I put a log after executing AlarmManager's setInexactRepeating, and it shows success executing setInexactRepeating, but the service is never started.

Here is the code to start the service:

 public void startService(Context context){
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(Home.this, NotificationService.class);
    int minutes = 1 ;
    PendingIntent pi = PendingIntent.getService(Home.this, 0, i, 0);
    am.cancel(pi);

        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
           System.currentTimeMillis(),
            minutes*60*1000, pi);   
        Log.e("Service Started","Halilujia");
}

Here is the declaration in the manifest:

     <service
      android:name=".services.NotificationService"
      android:enabled="true">

 </service>

public class NotificationService extends Service {

private WakeLock mWakeLock;
private Context activity = getApplicationContext();
@Override
public IBinder onBind(Intent intent) {
    return null;
}


private void handleIntent(Intent intent) {
    // obtain the wake lock
    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DebuggingTag");
    mWakeLock.acquire();

    // check the global background data setting
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    if (!cm.getBackgroundDataSetting()) {
        stopSelf();
        return;
    }
    Log.e("Just before request","Just before Request");
            // send http request here and create notification

}


@Override
public void onStart(Intent intent, int startId) {
Log.e("Onstart Called","Onstart has been Called");
handleIntent(intent);
}


@Override
 public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Onstart Called","Onstart has been Called");
handleIntent(intent);
return START_NOT_STICKY;
 }

 public void onDestroy() {
super.onDestroy();
mWakeLock.release();
 }


}

Thanks

Was it helpful?

Solution

Based on the comments, this is a new (edited) answer...

Your manifest declaration for the Service is...

<service
    android:name=".services.NotificationService"
    android:enabled="true">
</service>

...which is declaring NotificationService as being contained in a package called services. Example...

Main package is com.example.MyApp and the service is in com.example.MyApp.services.

Placing the code file for the service in /src/services doesn't change the package name / path used by the android:name attribute.

To resolve the issue either change the declaration to use android:name=".NotificationService or create a separate com.example.MyApp.services package and place the service code file in there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top