如何使用服务每小时显示本地通知

时间:2017-07-01 13:05:28

标签: android service alarmmanager android-notifications show

我想在每小时或特定秒使用服务显示本地通知,我已尝试实现此功能,但我没有成功。

我的代码如下所示

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
        notificationIntent.addCategory("android.intent.category.DEFAULT");

        PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar cal = Calendar.getInstance();
        Log.d("day for notification:::", String.valueOf(notification_day));

            cal.add(Calendar.MINUTE, notification_day);
alarmManager.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), 4 * 60 * 60, broadcast);

1 个答案:

答案 0 :(得分:2)

您的代码似乎没问题。 唯一可能有问题的是4 * 60 * 60的间隔太短,这是14.4秒。

此外,您似乎没有将意图指向特定的接收器。你应该这样做:

Calendar calendar = Calendar.getInstance();
Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)this.getSystemService(this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60, pendingIntent);

你应该抓住它:

public class AlarmReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(context, EVentsPerform.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


    NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
            context).setSmallIcon(R.drawable.applogo)
            .setContentTitle("text")
            .setContentText("text")
            .setWhen(when)
            .setContentIntent(pendingIntent)
    notificationManager.notify(yourId, mNotifyBuilder.build());

}

}

将此添加到您的清单文件中:

 <!-- permission required to use Alarm Manager -->
 <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

 <!-- Register the Alarm Receiver -->
 <receiver android:name="com.example.alarmmanagernotifcation.AlarmReceiver"/>