2014-06-24 3 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에서 토스트를보고있는 경우 서비스가 중지되고,하지만 난 당신이 당신의 기록이 계속 사실에 의해 혼동되고있다 생각합니다. 로깅은 별도의 스레드에서 발생하기 때문에 계속됩니다. 당신이 당신의 스레드뿐만 아니라 중지 확인하려면, 당신은 당신의 서비스에 간단한 변경의 몇 가지를 만들 수 있습니다

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

작동합니다. 정답으로 표시하고 upvoting하는 것을 잊지 마십시오. – HexAndBugs

관련 문제