如何每一分钟后运行广播接收器? [英] How to run BroadcastReceiver after every minute?

查看:222
本文介绍了如何每一分钟后运行广播接收器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个应用程序来监控每一分钟后网络。我使用一个BroadcastReceiver这一点。

I am developing an application to monitor the network after every minute. i am using a BroadcastReceiver for this.

我要每一分钟后执行广播接收器。

I want to execute the BroadcastReceiver after every minute.

我该怎么办呢?我可以在广播接收器使用视频下载()?

How can I do it? can i use Thread.sleep() in BroadcastReceiver?

什么情况下可以继续保持运行Android广播接收器?

Is it okay to continuously keep running BroadcastReceiver in android?

推荐答案

BroadcastReceievers被设计成只有当一些广播接收(系统广播或用户定义的广播)运行。如果您想运行一些code的每一分钟,你可以创建一个服务,并安排它使用报警管理器每分钟运行。您可以使用警报管理开始从您广播接收机的服务,它将运行的每一分钟。

BroadcastReceievers are designed to run only when some broadcast is received (System broadcast or user defined broadcast). In case you want to run some code every minute, you can create a service and schedule it for every minute run using an Alarm Manager. You can start the service from your broadcast receiver using alarm manager and it will run every minute.

在你的广播接收器,使用code的onRecieve()方法类似如下:

In the onRecieve() method of your broadcast receiver, use code similar to the below given:

PendingIntent service = null; 
Intent intentForService = new Intent(context.getApplicationContext(), YourService.class);
final AlarmManager alarmManager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
final Calendar time = Calendar.getInstance();
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
if (service == null) {
 service = PendingIntent.getService(context, 0,
                    intentForService,    PendingIntent.FLAG_CANCEL_CURRENT);
        }

        alarmManager.setRepeating(AlarmManager.RTC, time.getTime()
                .getTime(), 60000, service);

这篇关于如何每一分钟后运行广播接收器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆