AlarmManager完成定时通知

  Intent intent = new Intent(MainActivity.this, AutoReceiver.class);
                intent.setAction("VIDEO_TIMER");
                // PendingIntent这个类用于处理即将发生的事情

                PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                Log.e(TAG, "onClick: 点击启动定时任务" );
                // AlarmManager.ELAPSED_REALTIME_WAKEUP表示闹钟在睡眠状态下会唤醒系统并执行提示功能,该状态下闹钟使用相对时间
                // SystemClock.elapsedRealtime()表示手机开始到现在经过的时间
                //intervalMillis 时间 (毫秒值) (10*1000==10秒)
                am.setRepeating(AlarmManager.RTC_WAKEUP,
                        SystemClock.elapsedRealtime(), 10* 1000, sender);

创建广播

public class AutoReceiver extends BroadcastReceiver {
    private static final int NOTIFICATION_FLAG = 1;
    private NotificationManager manager;//通知
    Context context= Applictio.getContext();
    @SuppressLint("NewApi")
    @Override
    public void onReceive(Context context, Intent intent) {
        this.context=context;
        manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "chat";
            String channelName = "聊天消息";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            createNotificationChannel(channelId, channelName, importance);
        }
        Log.e("-----------", "onReceive: "+ intent.getAction());
        if (intent.getAction().equals("VIDEO_TIMER")) {
            Intent resultIntent = new Intent(context, ShowActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            Notification notification = new NotificationCompat.Builder(context, "chat")
                    .setAutoCancel(true)
                    .setContentTitle("收到聊天消息")
                    .setContentText("今天晚上吃什么")
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher))
                    .build();
            manager.notify(1, notification);
            // level16及之后增加的,API11可以使用getNotificatin()来替代
            notification.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。
            notification.defaults |= Notification.DEFAULT_VIBRATE;//使用默认的震动
            // 在Android进行通知处理,首先需要重系统哪里获得通知管理器NotificationManager,它是一个系统Service。
            NotificationManager manager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_FLAG, notification);// 步骤4:通过通知管理器来发起通知。如果id不同,则每click,在status哪里增加一个提示
            //关闭广播  这里最开始用的是取消注册好的广播,但是注销以后无法再次启动
//            context.getPackageManager().setComponentEnabledSetting( new ComponentName("广播的包名", AutoReceiver.class.getName()),
//                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
//                    PackageManager.DONT_KILL_APP);
            PendingIntent pendIntent1 = PendingIntent.getBroadcast(context, 0,
                    intent, 0);
            // 与上面的intent匹配(filterEquals(intent))的闹钟会被取消
            // 进行闹铃取消
            AlarmManager manager1 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            manager1.cancel(pendIntent1);

        }
    }

    //通知消息
    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager)context. getSystemService(
                Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }
}

在AndroidManifest中静态注册

  <!--定时 -->
        <receiver
            android:name="com.qytimes.aiyuehealth.AutoReceiver"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
        </receiver>

这就完成了,直接复制粘贴即可,如果有不理解的地方,私信即可

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页