我有一项服务,我想在后台每分钟执行一项任务。只要用户正在使用手机,它就不需要在手机处于睡眠状态时执行任务。我试图用一个IntentService来做这个,它设置如下:
public class CounterService extends IntentService{
public CounterService() {
super("CounterService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent,flags,startId);
}
@Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(this, "onhandleintent", Toast.LENGTH_SHORT).show();
while(true)
{
//one minute is 60*1000
try {
Thread.sleep(5 * 1000);
Toast.makeText(getApplicationContext(), "getting app count", Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
现在为了让功能正常工作我只想让它每5秒钟显示一次吐司,我会在一分钟之后将其更改。如果我已注释掉while(true)
,则会显示“onhandleintent”消息。但是,如果我运行以下代码,则不会显示Toasts。我该如何解决这个问题?
答案 0 :(得分:21)
这将每分钟向您的服务发送一个意图,而不会在您的活动中使用任何处理器时间
Intent myIntent = new Intent(context, MyServiceReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60); // first time
long frequency= 60 * 1000; // in ms
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);
调整MyServiceReceiver.class以匹配您的目标服务或活动。 documentation提供了更多详细信息来微调您的调用,例如您是否需要精确计时,在一天中的特定时间执行...
答案 1 :(得分:5)
您需要退出主线程以避免冒ANR的风险。
而是添加一个处理程序
Handler mHandler = new Handler();
...
@Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(this, "onhandleintent", Toast.LENGTH_SHORT).show();
mHandler.postDelayed( ToastRunnable, 5000);
//while(true)
//{
//one minute is 60*1000
//try {
// Thread.sleep(5 * 1000);
// Toast.makeText(getApplicationContext(), "getting app count",
//Toast.LENGTH_LONG).show();
//} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
//}
}
final Runnable ToastRunnable = new Runnable(){
public void run(){
Toast.makeText(getApplicationContext(), "getting app count",
Toast.LENGTH_LONG).show();
mHandler.postDelayed( ToastRunnable, 5000);
}
}
答案 2 :(得分:2)
这样做
private void ping() {
try {
//Your code here or call a method
} catch (Exception e) {
Log.e("Error", "In onStartCommand");
e.printStackTrace();
}
scheduleNext();
}
private void scheduleNext() {
mHandler.postDelayed(new Runnable() {
public void run() { ping(); }
}, 60000);
}
public int onStartCommand(Intent intent, int x, int y) {
mHandler = new android.os.Handler();
ping();
return START_STICKY;
}