Android : AlarmManager not start

2019-09-05 00:54发布

问题:

I must create an AlarmManager that repeating every seconds, I use this code

Intent in = new Intent(context,Tempo_Indietro.class);
in.putExtra("id_widget", appWidgetIds[i]);
PendingIntent pi = PendingIntent.getActivity(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pi);

but it don't start...why ??

回答1:

To start a Scheduled Activity: you can use like:

Step1: Setting for AlarmManager

    Intent intent =new Intent(context,AlarmReceiver.class);

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManger.RTC_WAKEUP,System.currentTimeMillis(), 1000, pi);

Step2: creating a BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver {

 //override onReceive(Context, Intent) method
 @Override public void onReceive(Context context, Intent intent)
 {
 //.........
    Intent i = new Intent(context,Tempo_Indietro.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);
//..........  
 }

}

Note: Don’t forget to include the newly created activity, receiver in the AndroidManifest.xml file.