我有一个警报应用程序应该每隔1分钟打印一次Toast消息。但是当它第一次运行时它只会执行一次。
这里是我的代码:
private class ConnectivityReceiver extends BroadcastReceiver{
MainActivity m= new MainActivity ();
private Timer mTimer;
private TimerTask mTimerTask;
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
wl.acquire(); Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // Every 1 minute i print the tost message. wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, ConnectivityReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 1, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, ConnectivityReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
答案 0 :(得分:3)
做一件事,
在第PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
行
替换为PendingIntent sender = PendingIntent.getBroadcast(context, **someUniqueId**, intent, 0);
其中 uniqueId 是整数,您生成或声明为“i ++”,其中i为public static int i;
希望这会起作用