如何在 android 中的另一个 activity 启动和停止服务

how to start service and stop it at another activity in android

my Service never stop until I uninstall the app #HELP!

服务class

public class LocationService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    GPSTracker myGps = new GPSTracker(getApplicationContext());
    Log.e("tracking...","");
    return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public boolean stopService(Intent name) {
    GPSTracker myGps = new GPSTracker(getApplicationContext());
        Log.e("STOPPED!","");
    return super.stopService(myGps);
  }
}

** 在登录时启动服务 Activity**

            Intent locationService = new Intent(Login.this, LocationService.class);
            startService(locationService);

** 在选项选择菜单中的员工 Activity 处停止服务 **

     @Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent serviceIntent;
    int id = item.getItemId();
    if (id == R.id.LogOut) {
        serviceIntent = new Intent(Employee.this, LocationService.class);
        stopService(serviceIntent);
        Log.e("OUT"," ");
         finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

在A和B的2个Activity中,你应该在B的onStop()中解绑服务,然后你就可以在A中调用stopService了。简单的把stopService(serviceIntent);可能会给你和关于泄漏服务连接的错误

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(i, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(i);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

在你的代码中看到你所做的是你已经停止了服务,但我没有看到你解除绑定,正确的程序是解除绑定然后停止它。

不要使用命令 startService(service)。

要在应用程序开始时启动服务,只需将其绑定到您的所有活动即可。这样,当活动被销毁时,服务停止。 解释得很透彻HERE

此外,如果您希望服务在应用程序关闭(但未销毁)时结束,只需将 unBindService 方法添加到重写的 onStop 方法即可。