Search code examples
androidnotificationsbroadcastreceiverandroid-servicealarmmanager

Receiver, service, alarmmanager and status bar notification


I have a receiver and service that run on device start up, but let`s say the user never turn off his device, how should I handle this?

How do I schedule status bar notification with alarmmanager from my receiver/service?

package it.bloomp.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class EventsNotificationService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Service created.");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service destroyed.");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onCreate();
        System.out.println("Service started.");
    }
}

...

package it.bloomp.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class EventsNotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, EventsNotificationService.class);
            context.startService(serviceIntent);
        }
    }
}

Solution

  • You can use some other kind of Broadcast receiver which is suitable to your requirements. Or you can set a time period to run your task periodically by using Timer class, something like this ;

    Timer time;
    time..scheduleAtFixedRate(new TimerTask() {            
            @Override
            public void run() {
               //Your task         
            }
        }, 0/*Start delay*/, 1000/*Delay period*/);
    

    Update : To schedule a notification you can do somethng like this:

    Intent intentSafety_Check_Service = new Intent(Activity_Add_Safety_Check.this, Safety_Check_Service.class);
    
        pendingIntent = PendingIntent.getService(Activity_Add_Safety_Check.this,                Integer.parseInt(currCheckID), intentSafety_Check_Service, 0);
    
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    
        Calendar calendar = Calendar.getInstance();
    
        calendar.setTimeInMillis(/*Your alarm date converted in milliseconds*/);
    
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);