我有一个简单的服务
public class UpdateService extends Service {
private int seconds;
final static String MY_ACTION = "MY_ACTION";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
timer.start();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
final CountDownTimer timer = new CountDownTimer(86400000, 1000) {
public void onTick(long millisUntilFinished) {
Util.saveInfo(getApplicationContext(), Util.SECONDS, seconds++);
Intent intent = new Intent();
intent.setAction(MY_ACTION);
sendBroadcast(intent);
}
public void onFinish() { }
};
}
当我关闭应用程序服务时停止工作。但是显示该服务正在运行。
我做错了什么?
更新
我将CountDownTimer更改为Thread,但问题仍然存在
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
Util.saveInfo(getApplicationContext(), Util.SECONDS, seconds++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
的OnStart()
if(!t1.isAlive())
t1.start();
答案 0 :(得分:0)
由于CountDown Timer
仅有效foreground
表示应用正在运行且未最小化或已关闭。您必须在Thread
中放置Service
,以便在特定时间执行。
试试这个:
public class LocalService extends Service
{
private static Timer timer = new Timer();
private Context ctx;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
ctx = this;
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
private final Handler toastHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
System.out.println("test");
}
};
}