嗨朋友我有一个问题需要解决...我想彻底销毁服务,一旦我从Activity调用onDestroy()方法。但我的问题是,我无法彻底销毁它..在后台继续运行,我正在分享我尝试的示例代码..
//Activity Class
public class ServiceToAct extends Activity {
private static final String TAG = "BroadcastEvent";
private Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(myService.BROADCAST_ACTION));
}
/*@Override
protected void onResume() {
super.onResume();
}*/
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
@Override
protected void onDestroy() {
stopService(intent);
Toast.makeText(this, "Destroy Completely", Toast.LENGTH_LONG).show();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
}
};
}
// service class
public class myService extends Service {
private static final String TAG = "BroadcastEvent";
public static final String BROADCAST_ACTION = "com.service.activity.myService";
private final Handler handler = new Handler();
Intent intent;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
intent = new Intent(BROADCAST_ACTION);
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "start", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendToUI);
handler.postDelayed(sendToUI, 1000);
}
@Override
public void onDestroy() {
super.onDestroy();
stopSelf();
//stopService(intent);
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
private Runnable sendToUI = new Runnable() {
@Override
public void run() {
myData();
handler.postDelayed(this, 10000);
}
};
private void myData() {
Log.d(TAG, "keep on entering");
Toast.makeText(this, "Keep on despling in UI", Toast.LENGTH_LONG).show();
sendBroadcast(intent);
}
}
这里实际上我想从服务更新我的UI,我的一切正常,但是如果我销毁它继续调用myData()方法的服务,并且如果我也关闭应用程序,我将获得Toast消息。 我的问题是,一旦服务被除去,我不想要那个祝酒词 我使用了stopService(intent)方法来销毁服务,但是后台方法myData()一直在调用
答案 0 :(得分:0)
停止服务完全使用此..
<强> myActivity.java 强>
@Override
public void onDestroy() {
stopService(intent);
super.onDestroy();
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
<强> service.java 强>
@Override
public void onDestroy()
{
stopSelf();
super.onDestroy();
}
答案 1 :(得分:0)
在更新UI后使用stopService()方法
或
而不是使用startService在活动中使用bindService。当活动破坏时,服务也会破坏
答案 2 :(得分:0)
你最好永远不要直接打电话给Xxx()。 在您的活动中使用stopService(Intent i),在您的服务中使用stopSelf()来停止。