在 android 应用程序中设置 notification/alarm

Setting notification/alarm in an android application

我正在为 java 教程构建一个简单的 android 应用程序,我想在其中保留一个稍后阅读选项,用户可以使用该选项安排阅读时间和我的应用程序的指定时间应该给用户一个通知。即使我的应用程序当时没有打开,他也应该在通知中收到通知 bar.I 我是 android 的新手,不知道该怎么做 this.Can 有人帮帮我吗?作为一个新手详细的说明可以提前更helpful.Thanks:-)

使用AlarmManager解决您的问题。当收到警报时,您也可以发送通知。

请参阅 android 的警报实施教程中的 this 示例应用程序。

要安排延迟通知,您

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());
        }

    }
}

不要忘记在清单中声明它:

       <receiver
        android:name="your.package.name.MyReceiver"
        android:exported="false" />

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) 大功告成

//免责声明:没有编译代码,可能有错别字。剩下的就是你的功课了 ;)