我在服务方面有点问题。
服务:
public class MyService extends Service {
public MyService() {
}
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) {
timer.cancel();
task.cancel();
return super.stopService(name);
}
@Override
public void onDestroy(){
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
super.onDestroy();
}MainActivity:
public class ClientSocket extends ActionBarActivity {
CheckBox enablecheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_socket);
enablecheck = (CheckBox)findViewById(R.id.enablecheck);
enablecheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(enablecheck.isChecked()){
startService(new Intent(ClientSocket.this, MyService.class));
}else
{
stopService(new Intent(ClientSocket.this, MyService.class));
}
}
});
}舱单档案:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light" >
<activity
android:name=".ClientSocket"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
</service>
</application>
我只是在测试,当我试图停止服务时,函数onDestroy()将被调用,但不要停止该服务。service/android:exported和android:enable都是真的。
有什么帮助吗?
发布于 2015-02-23 22:22:39
Timer实例创建一个后台线程。如果要完全停止服务,还需要停止线程。Timer有一个cancel()方法,您可以在onDestroy()方法中调用它来终止计时器。
此外,导出服务意味着其他应用程序(进程)可以访问它。你很可能不需要这个。
发布于 2015-02-23 22:46:33
代码中的问题是对什么的误解
@Override
public boolean stopService(Intent name) {
timer.cancel();
task.cancel();
return super.stopService(name);
}真的是这样。
它不是在服务停止时调用的回调。相反,它是在stopService上重写Context方法,您调用该方法来停止服务(就像在示例中的活动中所做的那样)。
实际上,代码中对stopService的覆盖根本没有影响。
timer.cancel();
task.cancel();应该放在服务的onDestroy方法中。
https://stackoverflow.com/questions/28684383
复制相似问题