0

Bound Service を学習するためのサンプル アプリがあります。起動時の通知を設定します。通知をクリックしてアプリをN回起動した場合、アプリを閉じてサービスを停止するには、「戻る」ボタンをN回クリックする必要があります。「戻る」を 1 回クリックすると、アプリが停止します。http://developer.android.com/guide/components/bound-services.htmlの Android デベロッパー ガイドから: 「一度に複数のクライアントがサービスに接続できます。ただし、システムはサービスの onBind() メソッドを呼び出して、最初のクライアントがバインドする場合にのみ IBinder を取得します。その後、システムは、同じ IBinder をバインドする追加のクライアントに配信しますが、呼び出しは行われません。最後のクライアントがサービスからバインドを解除すると、システムはサービスを破棄します (サービスが startService() によって開始された場合を除く)。そのため、通知をクリックするたびに別のクライアントがバインドされ、次にバインドを解除する必要があると想定しています。この望ましくない動作を取り除くにはどうすればよいですか?

関連コード:

public class MainActivity extends Activity {
private LocalService mBoundService;
boolean mIsBound = false;

...........

@Override
protected void onStart() {
    super.onStart();
    if (!mIsBound)
        doBindService();
};

.............
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        if (mIsBound) {
            int num = mBoundService.getRandomNumber();
            Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
        }
    }
    return super.onOptionsItemSelected(item);
}

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
     mBoundService = ((LocalService.LocalBinder) service).getService();
        // Tell the user about this for our demo.
        Toast.makeText(MainActivity.this, R.string.local_service_connected,
                Toast.LENGTH_SHORT).show();
    }

........... 
void doBindService() {
    // Establish a connection with the service.  We use an explicit
    // class name because we want a specific service implementation that
    // we know will be running in our own process (and thus won't be
    // supporting component replacement by other applications).
    bindService(new Intent(MainActivity.this, 
            LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

    }
}
4

0 に答える 0