2014-06-24 57 views
2

我是新來的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(); 
    } 
} 
+0

看看這個主題是否幫助你:http://stackoverflow.com/questions/2176375/service-wont-stop-when-stopservice-method-is-called – PedroHawk

回答

0

如果您在onDestroy中看到Toast,服務即將停止,但我認爲您對日誌繼續存在的事實感到困惑。記錄繼續,因爲它發生在一個單獨的線程。如果你想使你的線程停止,以及,你可以做一些簡單的改變您的服務:

public class MyService extends Service { 

    private Thread mThread; 

    @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) { 
     mThread = new Thread() { 
      public void run() { 
       while (!interrupted()) { 
        Log.v(Tag,"Thread"+i); 
       } 
      } 
     }.start() 
     return START_STICKY; 
    } 
    @Override 
    public void onDestroy() { 
     mThread.interrupt(); 
     super.onDestroy(); 
     Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); 
    } 
} 

的使用注意事項mThread的和中斷的循環檢查()。我沒有測試過,但我相信它應該可以工作。

+0

雅它的工作比一噸 – user3771709

+0

如果它的工作,請記得標記答案是正確的,並考慮提高它。 – HexAndBugs