我是新來的android。我想要停止MainActivity的Service
。但我沒有得到這個。在調用stopService()
時,它只顯示Toast
消息。我觀察到服務仍在後臺運行。如何停止服務。這是我的示例代碼。我的服務不被破壞 - 如何停止服務
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Method to start the service
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
// Method to stop the service
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
static int i=0;
private static final String Tag="MyService";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread() {
public void run() {
while (true) {
Log.v(Tag,"Thread"+i);
}
}
}.start()
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
看看這個主題是否幫助你:http://stackoverflow.com/questions/2176375/service-wont-stop-when-stopservice-method-is-called – PedroHawk