我第一次尝试创建一个服务,当应用程序是手机的背景时,一旦选中切换按钮,它就会每 15 秒从 Activity 中运行一个方法,到目前为止,教程还没有帮助;到目前为止,这是我的代码。如果我在这里看起来很愚蠢,请原谅我,这是我第一次使用服务。
服务代码
package com.example.adrian.trucktracker;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import java.util.Timer;
import java.util.TimerTask;
public class AutoUpdateService extends Service {
Locator locator = new Locator();
Timer myTimer = new Timer();
private class MyTimerTask extends TimerTask
{
@Override
public void run() {
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
locator.TemperatureCatch();
}
}, 1000 );
}
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
MyTimerTask myTimerTask = new MyTimerTask();
myTimer.scheduleAtFixedRate(myTimerTask, 0, 15000);
}
@Override
public void onDestroy() {
super.onDestroy();
myTimer.cancel();
stopSelf();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
我的切换按钮代码
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
startService(new Intent(this,AutoUpdateService.class));
}
else
{
stopService(new Intent(this,AutoUpdateService.class));
}
最佳答案
您正确使用服务。不要使用 Timer,因为它是您不需要的额外线程。你可以做的是使用 AlarmManager安排您的服务 Intent 每 15 秒(间隔)启动一次。这将通过在您的服务中调用 onStartCommand 来触发您的服务的间隔时间,您可以通过从 onStartCommand 的参数中读取(如果需要) Intent 来执行您需要的任何操作。
关于java - Android如何在应用程序处于手机后台时运行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25253520/