如何在新线程中启动服务?

时间:2012-01-13 14:48:42

标签: android android-service

如何在新线程中启动我的服务。我查看了其他问题,但它对我有用。在正常运行和在单独的线程中运行时,我需要在服务中进行哪些更改?

4 个答案:

答案 0 :(得分:8)

将您的public void onStart(final Intent intent, final int startId)方法重命名为_onStart并使用此新的onStart实施:

 @Override
 public void onStart(final Intent intent, final int startId) {
     Thread t = new Thread("MyService(" + startId + ")") {
         @Override
         public void run() {
             _onStart(intent, startId);
             stopSelf();
         }
     };
     t.start();
 }

 private void _onStart(final Intent intent, final int startId) {
     //Your Start-Code for the service
 }

适用于API级别5及以上

public void onStart(Intent, int)已在API级别5弃用。应将其替换为public int onStartCommand(Intent, int)

@Override
public int onStartCommand(final Intent intent, final int startId){
    //All code from 'onStart()' in above placed here as normal.
}

private void _onStart(final Intent intent, final int startId) {
     //Your Start-Code for the service
}

答案 1 :(得分:3)

我认为您不能在新线程中启动您的服务,但您可以做的是在您的服务中启动一个新线程。

这是因为与活动一样,服务具有在主线程上运行的生命周期方法。

因此,您的服务将在主线程上运行,但它将在需要时创建的新线程上进行繁重的工作。

我希望它有所帮助..

答案 2 :(得分:2)

引自http://developer.android.com/reference/android/app/Service.html

“请注意,服务与其他应用程序对象一样,在其托管进程的主线程中运行。这意味着,如果您的服务将进行任何CPU密集型(如MP3播放)或阻止(如网络)操作,它应该生成自己的线程来完成这项工作。有关这方面的更多信息可以在进程和线程中找到.IntentService类可用作Service的标准实现,它有自己的线程,用于调度其工作完成“。

答案 3 :(得分:-1)

在我的项目中,我有这样的人,这是有效的:

Thread welcomeThread = new Thread() {
@Override
public void run() {
    try {
        super.run();
        while (isMyServiceRunning() != true) {
            sleep(100);
        }
    } catch (Exception e) {
        System.out.println("EXc=" + e);
    } finally {
        Intent i = new Intent(getApplicationContext(), MainPage.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }
}
};

welcomeThread.start();