0


MainActivity 在 onCreate 中启动我的 TestService 并在 onStart 方法中绑定。AsyncThread 在 TestService onStartCommand 中启动。bind 和 unbind 方法以正确的顺序调用。一切都很完美,绝对没有问题:)。

问题从这里开始:如果 MainActivity 被终止,那么运行的异步线程也会停止,没有任何中断异常,但 TestService 仍在运行,我可以在运行应用程序设置中检查。请帮助我找出线程停止工作的原因。

PS:我与 Thread/Handler 进行了交叉检查,但结果相同。

MainActivity 和服务代码在这里:

public class MainActivity extends Activity implements IServiceInterface {

boolean mBound = false;
TestService mTestService = null;

@Override
protected void onCreate(Bundle savedInstanceState) {

    Intent serviceIntent = new Intent(this, TestService.class);
    startService(serviceIntent);

}

@Override
protected void onStart() {
    super.onStart();
    // Bind to LocalService
    NSLogger.i("service binding....");
    Intent intent = new Intent(this, TestService.class);
    bindService(intent, mBindConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    if (mBound) {
        NSLogger.i("service unbinding....");
        unbindService(mBindConnection);
        mBound = false;
    }

}

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mBindConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,
            IBinder service) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        NSLogger.i("UI is connected to service");
        LocalBinder binder = (LocalBinder) service;
        mTestService = binder.getTestService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        NSLogger.i("UI is disconnected from service");
        mBound = false;
        mTestService = null;
    }
};

}


public class TestService extends Service implements Runnable, Handler.Callback{

 // Binder given to inproc clients
private final IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent intent) {
    mUIIsBound = true;
    return mBinder;
}

public boolean onUnbind (Intent intent) {
    mUIIsBound = false;
    NSLogger.i("unbind service");
    return true;
}


public class LocalBinder extends Binder {
    TestService getTestService() {
        return TestService.this;
    }

}

public void onDestroy() {
    //NEVER CALLED.
}

public int onStartCommand(Intent intent2, int flags, int startId) {
    NSLogger.i("TestService start!");
    new DownloadConfiguration().execute();
    return START_STICKY;
}

private class DownloadConfiguration extends AsyncTask<Void, Integer, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
         try {
             NSLogger.i("before sleep");
             Thread.sleep(5000);
             NSLogger.i("After sleep");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return true;
    }
}
4

0 回答 0