如何使用服务每小时显示一次本地通知 [英] How to show local notification every hour using service
本文介绍了如何使用服务每小时显示一次本地通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用服务在每小时或每秒钟显示本地通知,我曾尝试实现此功能,但没有成功。
I want to show local notification on every hour or particular seconds using service, I have tried to implement this functionality, but I didn't got success.
我的代码如下所示
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);
推荐答案
您的代码似乎还可以。
唯一有问题的是间隔4 * 60 * 60太短,即14.4秒。
Your code seems to be OK. The only thing that can be problematic is the interval 4*60*60 is too short which is 14.4 seconds.
此外,您似乎还没有将意图定向到特定的接收者。您应该这样做:
Moreover it seems like you're not directing the intent to a specific receiver. you should do like this:
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());
}
}
将此添加到您的清单文件:
Add this to your manifest file:
<!-- 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"/>
这篇关于如何使用服务每小时显示一次本地通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文