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>

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 AlarmManager 实现定时重置流量统计可以分为以下几个步骤: 1. 在 AndroidManifest.xml 文件中添加以下权限: ```xml <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> ``` 2. 创建一个 BroadcastReceiver,用于接收定时任务的触发事件,并在其中实现重置流量统计的逻辑。例如: ```java public class TrafficStatsResetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 重置流量统计信息 TrafficStats.clearAllStats(); } } ``` 3. 在 AndroidManifest.xml 文件中注册 BroadcastReceiver,并且添加一个 ACTION_BOOT_COMPLETED 的 intent-filter,以便在设备启动时启动定时任务。例如: ```xml <receiver android:name=".TrafficStatsResetReceiver" android:enabled="true" android:exported="false"> <intent-filter> <action android:name="com.example.trafficstatsreset.ACTION_RESET_TRAFFIC_STATS" /> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> ``` 4. 在应用程序启动时注册一个定时任务,例如: ```java private void registerTrafficStatsResetTask(Context context) { // 创建一个 PendingIntent,用于触发定时任务 Intent intent = new Intent(context, TrafficStatsResetReceiver.class); intent.setAction("com.example.trafficstatsreset.ACTION_RESET_TRAFFIC_STATS"); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // 获取 AlarmManager 实例 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // 计算定时任务的触发时间 long triggerTime = System.currentTimeMillis() + 24 * 60 * 60 * 1000; // 每天重置一次流量统计 // 注册定时任务 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, 24 * 60 * 60 * 1000, pendingIntent); } ``` 在上述代码中,我们创建了一个 PendingIntent,并将其传递给 AlarmManager 的 setRepeating 方法,以便注册一个每天重置一次流量统计的定时任务。需要注意的是,我们设置的定时任务触发时间是当前时间加上一天的时间间隔,这样可以确保定时任务在第二天凌晨触发。 5. 在应用程序启动时调用 registerTrafficStatsResetTask 方法,注册定时任务即可: ```java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 注册定时任务 registerTrafficStatsResetTask(this); } ``` 经过上述步骤,您就可以使用 AlarmManager 来实现定时重置流量统计的功能了。需要注意的是,使用 AlarmManager 时需要仔细管理定时任务的触发时间和间隔,以确保应用程序的稳定性和安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值