如何在android中的新线程中启动服务

bHa*_*aTh 29 android

我是这个机器人的新手.我正在使用服务做一些后台工作.所以我从我的活动开始服务如下.

        getApplicationContext().bindService(
        new Intent(getApplicationContext(), MyAndroidUpnpServiceImpl.class),
        serviceConnection,
        Context.BIND_AUTO_CREATE
    );
Run Code Online (Sandbox Code Playgroud)

但问题是android活动被阻止了.直到服务,

         onServiceConnected(ComponentName className, IBinder service){ ..}
Run Code Online (Sandbox Code Playgroud)

被叫回来.所以我搜索了这个.我开始知道我必须在新线程中开始我的服务.所以请任何人帮我这样做.

Sam*_*muh 38

要从活动内部创建和启动新线程,您可以说:

Thread t = new Thread(){
public void run(){
getApplicationContext().bindService(
        new Intent(getApplicationContext(), MyAndroidUpnpServiceImpl.class),
        serviceConnection,
        Context.BIND_AUTO_CREATE
    );
}
};
t.start();
Run Code Online (Sandbox Code Playgroud)

此外,如果您需要它以供以后使用,请缓存bindservice返回的值(如果有).

  • 嗨Samuh工作.现在它没有阻止我的活动,直到服务开始..非常感谢你的帮助..我还有一个问题.我将在下一条评论中发表.. (2认同)

Mau*_*vin 14

任何使用Threads,Runnables,AsyncTask或其他服务的解决方案都会遇到一个常见问题.

服务将阻止调用Activity,直到服务启动.因此在某些情况下无法有效地处理服务.

解决方案是使用IntentService子类.

如何实现的示例:

public class MyCustomService extends IntentService 
{   
    private DatabaseAdapter mAdapter;

    public MyCustomService() {
        super("MyCustomService");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
        super.onStartCommand(intent, flags, startId);
        Toast.makeText(this, "MyCustomService Started", Toast.LENGTH_LONG).show();

        // Don't let this service restart automatically if it has been stopped by the OS.
        return START_NOT_STICKY;
    }

    @Override
    protected void onHandleIntent(Intent intent) 
    {
        Toast.makeText(this, "MyCustomService Handling Intent", Toast.LENGTH_LONG).show();
        // INSERT THE WORK TO BE DONE HERE
    }
}
Run Code Online (Sandbox Code Playgroud)

onCreate()和onDestroy也可以覆盖,只要super.onWhatever()在它们内部调用即可.

  • 你不能用IntentService做所有事情.服务有自己的用途. (2认同)