我在服务上编写了一个方法,每 x 秒运行一次。但也存在一些问题。
我做的是
public class noti extends Service {
Context mcont;
private Handler myhandler ;
private long RETRY_TIME = 15000;
private long START_TIME = 2000;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onStart(Intent intent, int startId) {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mcont=this;
myhandler= new Handler();
myhandler.postDelayed(myRunnable, START_TIME);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
try {
myhandler.removeCallbacks(myRunnable);
} catch (Exception e) {
// TODO: handle exception
}
}
private Runnable myRunnable = new Runnable() {
public void run() {
try {
new get_notifyalert_service(mcont).execute("") ;
} catch (Exception e) {
// TODO: handle exception
}
myhandler.postDelayed(myRunnable, RETRY_TIME);
}
};
}
这是正确的方法吗?
在手机上,当我检查 settings->apps->running-apps 时,它说有时会重新启动并且需要很长时间
提前致谢
最佳答案
我在您的解决方案中发现了两个问题:
首先:您的命令确实会定期激活,但它们会这样做on the main thread .在许多情况下,也许是大多数情况下,您希望定期处理在单独的线程上运行。
如果这是你想要的,计时器将是更好的选择:
t = new Timer();
task = new TimerTask() {
@Override
public void run() {
// do periodical action <-------------
}
};
t.scheduleAtFixedRate(task, 0, 1000);
第二:您的服务迟早会被 Android 回收,停止期刊 处理。
对于许多应用来说,这不是真正的问题。您不希望后台逻辑一直运行。
如果您不是这种情况,请将您的服务声明为前台服务(即保证不会被 Android 杀死):
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
..或者,至少,将其设置为粘性的:
public class StickyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
}
关于java - 这是在服务中每 x 秒重复一次方法的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24653979/