lundi 13 février 2017

About AlarmManager in Android

Vote count: 0

I know that by using AlarmManager, you can start a service at a specific time, and to register an alarm, you will need to set it in the "onCreate" method of your activity. The problem is, the "onCreate" method will be called every time the application is open, and thus the alarm(s) will actually be set again and again. Do Java and Android have some automatic mechanisms to avoid this kind of repetitive setting?

public class MyActivity extends Activity {
    ...
    MyAlarmReceiver alarm = new MyAlarmReceiver();
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // this set the alarm for message notification
        alarm.setAlarm(this);
    }
    ...
}

and,

public class MyAlarmReceiver extends WakefulBroadcastReceiver {
    ...
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, MyService.class);
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, service);
        // END_INCLUDE(alarm_onreceive)
    }

    public void setAlarm(Context context) {
        // This intent is used in alarm
        Intent intent = new Intent(context.getApplicationContext(), MyAlarmReceiver.class);
        // Create a PendingIntent to be triggered when the alarm goes off
        PendingIntent pIntent = PendingIntent.getBroadcast(context, reqCode, intent, PendingIntent.FLAG_ONE_SHOT);
        ... //Set the alarm
    }
}

and MyService is just a class extends Service.

asked 34 secs ago

Let's block ads! (Why?)



About AlarmManager in Android

Aucun commentaire:

Enregistrer un commentaire