Android 如何从调用活动类调用Service类的stopservice()方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3165190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call stopservice() method of Service class from the calling activity class
提问by Hare-Krishna
I am trying to call my service class's stopService() method from my activity. But I dont know how to access stopservice method from my activity class. I have the below code but its not working...........
我试图从我的活动中调用我的服务类的 stopService() 方法。但我不知道如何从我的活动类访问 stopservice 方法。我有下面的代码,但它不起作用......
This is HomeScreen class:
这是 HomeScreen 类:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
enablecheck = (CheckBox)findViewById(R.id.enablecheck);
enablecheck.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(enablecheck.isChecked()){
startService(new Intent(HomeScreen.this, AutoService.class));
}else
{
stopService(new Intent(HomeScreen.this, AutoService.class));
}
}
});
}
This is Service Class:
This is Service Class:
public class AutoService extends Service {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Auto Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer = new Timer();
timer.scheduleAtFixedRate(task = new TimerTask(){
public void run()
{
System.out.println("done");
}
}, delay, period);
}
@Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
Any suggestion highly appreciable. Thanks and Regards Mintu
任何建议都非常值得赞赏。感谢和问候 Mintu
回答by Jorgesys
In fact to stopping the servicewe must use the method stopService()
and you are doing in right way:
实际上,要停止服务,我们必须使用该方法,stopService()
并且您正在以正确的方式进行操作:
Startservice:
启动服务:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);
Stopservice:
停止服务:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);
if you call stopService()
, then the method onDestroy()
in the service is called (NOT the stopService()
method):
如果调用stopService()
,则调用onDestroy()
服务中的stopService()
方法(不是方法):
@Override
public void onDestroy() {
timer.cancel();
task.cancel();
Log.i(TAG, "onCreate() , service stopped...");
}
you must implement the onDestroy()
method!.
你必须实现这个onDestroy()
方法!。
Here is a complete exampleincluding how to start/stop the service.
这是一个完整的示例,包括如何启动/停止服务。
回答by Juri
I actually used pretty much the same code as you above. My service registration in the manifest is the following
我实际上使用了与上面几乎相同的代码。我在清单中的服务注册如下
<service android:name=".service.MyService" android:enabled="true">
<intent-filter android:label="@string/menuItemStartService" >
<action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
</intent-filter>
</service>
In the service class I created an according constant string identifying the service name like:
在服务类中,我创建了一个相应的常量字符串来标识服务名称,例如:
public class MyService extends ForeGroundService {
public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
...
}
and from the according Activity I call it with
从相应的 Activity 我称之为
startService(new Intent(MyService.MY_SERVICE));
and stop it with
并停止它
stopService(new Intent(MyService.MY_SERVICE));
It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.
它完美地工作。尝试检查您的配置,如果您没有发现任何异常,请尝试调试您的 stopService 是否正确调用。
回答by neevek
@Juri
@Juri
If you add IntentFilters for your service, you are saying you want to expose your service to other applications, then it may be stopped unexpectedly by other applications.
如果您为您的服务添加 IntentFilters,您是说您想将您的服务公开给其他应用程序,那么它可能会被其他应用程序意外停止。
回答by Robby Pond
That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopServicereturns a boolean indicating whether or not it was able to stop the service.
当您取消选中该复选框时,它看起来应该停止服务。日志中是否有任何异常?stopService返回一个布尔值,指示它是否能够停止服务。
If you are starting your service by Intents, then you may want to extend IntentServiceinstead of Service. That class will stop the service on its own when it has no more work to do.
如果您通过 Intents 启动您的服务,那么您可能需要扩展IntentService而不是 Service。当它没有更多工作要做时,该类将自行停止服务。
AutoService
汽车服务
class AutoService extends IntentService {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
public onCreate() {
timer = new Timer();
timer = new TimerTask() {
public void run()
{
System.out.println("done");
}
}
}
protected void onHandleIntent(Intent i) {
Log.d(TAG, "onHandleIntent");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer.scheduleAtFixedRate(timerTask, delay, period);
}
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
回答by AndroidDev
In Kotlin you can do this...
在 Kotlin 中,你可以这样做......
Service:
服务:
class MyService : Service() {
init {
instance = this
}
companion object {
lateinit var instance: MyService
fun terminateService() {
instance.stopSelf()
}
}
}
In your activity (or anywhere in your app for that matter):
在您的活动中(或在您的应用程序中的任何地方):
btn_terminate_service.setOnClickListener {
MyService.terminateService()
}
Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.
注意:如果您有任何挂起的意图在 Android 的状态栏中显示通知,您可能也希望终止它。