0


MainActivity は onCreate で TestService を開始し、onStart メソッドでバインドします。AsyncThread は TestService onStartCommand で開始されます。bind メソッドと unbind メソッドは正しい順序で呼び出されます。すべてが完全に機能し、まったく問題ありません:)。

問題はここから始まります: MainActivity が終了すると、実行中の非同期スレッドも中断例外なしで停止しますが、TestService はまだ実行中であり、実行中のアプリケーション設定で確認できます。スレッドが機能しなくなる理由を見つけるのを手伝ってください。

PS: Thread/Handler とクロスチェックしましたが、結果は同じです。

MainActivity と Service コードは次のとおりです。

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