我正在阅读有关Android服务的信息,尤其是我想到了这一点
一个应用程序位于前台时,它可以创建并运行两个应用程序 免费提供前台和后台服务。当应用进入 背景,它有一个几分钟的窗口,它仍然在 允许创建和使用服务。在该窗口的结尾,该应用 被认为是空闲的。此时,系统会停止该应用的 后台服务,就像该应用已调用了“服务” Service.stopSelf()方法。
在下面的代码中,当应用程序在大约一分钟后进入后台时,服务被销毁,但线程仍在执行。
为什么首先要终止服务?如果我要执行下载过程而不希望成为前台进程怎么办?
public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
Log.d("sssssssss",msg.toString()+"sssssssssss");
while(true){
Log.d("sssssssss","sssssssssss");
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
//stopSelf(msg.arg1);
}
}
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work doesn't disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
答案 0 :(得分:0)
Service
执行干净的处理。您的线程不会永远运行,我认为30分钟是在终止应用程序进程之前的硬限制。详细了解Background Execution Limits文档。