Android 如何从其他活动调用stopService?

Android 如何从其他活动调用stopService?,android,Android,android编程新手。 您能告诉我如何将视图作为参数传递吗 public class MainActivity extends ActionBarActivity { ... public void stopService(View view) { stopService(new Intent(getBaseContext(), MyService.class)); } } public class MySmsReceiver extends BroadcastRecei

android编程新手。 您能告诉我如何将视图作为参数传递吗

public class MainActivity extends ActionBarActivity {
  ...
  public void stopService(View view) {
    stopService(new Intent(getBaseContext(), MyService.class));
  }
}

public class MySmsReceiver extends BroadcastReceiver {
  ...
  MainActivity obj = new MainActivity();
  obj.stopService();
}
我已经正确地编写了MyService.java


谢谢

首先,您必须在onStop()中解除服务与上一活动的绑定。否则,您可能会遇到窗口泄漏异常

将停止服务的代码放入应用程序类中

public class AppController extends Application {
  private static AppController mInstance;

  public static synchronized AppController getInstance() {
    return mInstance;
  }
  .........

  public void stopService(View view) {
    stopService(new Intent(getBaseContext(), MyService.class));
  }
}
然后,您可以从任何类获取应用程序对象,并且可以从任何活动停止服务,但在此之前,您必须在
onStop()
中从其他活动解除服务绑定

要从任何位置停止服务,请致电:

AppController.getInstance().stopService();

看这里,我正在慢慢理解这一点。现在,这似乎奏效了<代码>context.startService(新意图(context,MyService.class));stopService(新的意图(context,MyService.class))感谢所有链接。嗨,用户,请您详细解释一下。或者请提供一个例子?我在MyService.java中有onStartCommand()和onDestroy。public int-onStartCommand(Intent-Intent,int-flags,int-startId){//让它继续运行,直到停止。Toast.makeText(这个“服务已启动”,Toast.LENGTH_LONG)。show();return START_STICKY;}@Override public void-onDestroy(){super.onDestroy();Toast.makeText(这个,“服务已销毁”,Toast.LENGTH_LONG).show()}如果您的服务是绑定服务,那么您必须从同一上下文调用unboundService()。检查这是否对我有效…谢谢,您让我免于了一个大麻烦:)