我正在为java教程构建一个简单的Android应用程序,其中我想保留一个稍后阅读选项,用户可以使用该选项安排时间进行阅读,并且在指定时间我的应用程序应该向用户发出通知.即使我的应用程序当时没有打开,他也应该在通知栏中收到通知.我是android的新手,不知道怎么做.有人可以帮帮我吗?作为ai是新手的详细解释可能会更有帮助.谢谢提前:-)
要安排延迟通知,您
1)创建一个BroadcastReceiver
将接收事件:
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //you might want to check what's inside the Intent if(intent.getStringExtra("myAction") != null && intent.getStringExtra("myAction").equals("notify")){ NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.yourIcon) //example for large icon .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)) .setContentTitle("my title") .setContentText("my message") .setOngoing(false) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setAutoCancel(true); Intent i = new Intent(context, YourTargetActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity( context, 0, i, PendingIntent.FLAG_ONE_SHOT ); // example for blinking LED builder.setLights(0xFFb71c1c, 1000, 2000); builder.setSound(yourSoundUri); builder.setContentIntent(pendingIntent); manager.notify(12345, builder.build()); } } }
不要忘记在Manifest中声明它:
2)安排行动(假设你从一个行动Activity
):
//will fire in 60 seconds long when = System.currentTimeMillis() + 60000L; AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, MyReceiver.class); intent.putExtra("myAction", "mDoNotify"); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); am.set(AlarmManager.RTC_WAKEUP, when, pendingIntent);
3)你完成了
//免责声明:没有编译代码,错别字可能.剩下的就是你的作业;)