报警应用中的广播接收器

时间:2017-11-04 18:22:31

标签: android broadcast alarm receiver

在警报应用程序中,用户可以设置无限量的警报吗? 我在我的项目中处理警报选项,我意识到它的工作只有一次。如果我想要能够发出许多警报,应该如何使用Threads或IntentFilter,或者其他什么呢?

public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    String title = intent.getStringExtra("Title");
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent myIntent = new Intent();
    System.out.println("Title: " + title);
    switch (title){
        case "Weight":
            myIntent = new Intent(context, WeightActivity.class);
            break;
        case "Measure":
            myIntent = new Intent(context, measurActivity.class);
            break;
        case "Pr":
            myIntent = new Intent(context, PrsActivity.class);
            break;
        case "Macros":
            myIntent = new Intent(context, DietActivity.class);
            break;
    }

    myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.dumbbell)
            .setContentTitle("Tracker")
            .setContentText(title)
            .setAutoCancel(true);

    notificationManager.notify(1, builder.build());
}

}

1 个答案:

答案 0 :(得分:0)

这就是 requestCodes

的原因

请注意 requestCode , 您只需在设置警报时为PendingIntent使用不同的请求代码。

public setMyAlarm(int requestCode){

AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);

alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() +
        60 * 1000, alarmIntent);
}

由于requestCode的类型是int,因此应该足以设置大量的警报。

另外,对于取消闹钟,你必须提到具有相同requestCode的Pending intent,你曾经设置闹钟。

请不要误解你的通知的待定​​内容。