启动和停止服务

时间:2019-06-21 13:08:12

标签: android service

我有一个这样的代码,单击按钮即可运行

if (isMyServiceRunning(PlayerService.class)) {
        stopService(mIntent);
        unbindService(serviceConnection);
    } else {
            startService(mIntent);
            bindService(mIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

当我单击按钮并且我的服务未运行时,服务开始工作(在这里一切正常) 当我单击按钮并运行服务时,服务停止并销毁(在这里一切正常) 但是当我单击以使服务开始工作时,服务无法正常工作

我的服务

public class PlayerService extends Service {

private final IBinder binder = new LocalBinder();

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return binder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    doAnything();

    return START_STICKY;
}
public class LocalBinder extends Binder {
    PlayerService getService() {
        return PlayerService.this;
    }
}

}

服务连接

    private ServiceConnection serviceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {

        PlayerService.LocalBinder binder = (PlayerService.LocalBinder) service;
        myService = binder.getService();
        Log.d("TEST", "MainActivity onServiceConnected");
        bound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        Log.d("TEST", "MainActivity onServiceDisconnected");
        bound = false;
    }
};

0 个答案:

没有答案