2016-03-23 8 views
0

Androidで作成したサービスを終了できませんでしたが、stopServiceの後も実行されたままです。次のようなサービスを開始:サービスを正しく終了するには、stopService()が機能していませんか?

Intent i = new Intent(this, MyService.class); 
    startService(i); 

関連マニフェストエントリ:

<service android:name=".services.MyService" ></service> 

いくつかの活動全体に持続しますので、私はIntentServiceを使用しなかったたMyServiceの要旨:

package com.sample.app.services; 

public class MyService extends Service { 

public static final String TAG = MyService.class.getSimpleName(); 
private Handler handler; 

protected void onHandleIntent(Intent intent) { 


    handler.post(new Runnable() { 
     @Override 
     public void run() { 
      Toast.makeText(getBaseContext(), "MyService Intent... Start", Toast.LENGTH_LONG).show(); 
     } 
    }); 

} 


@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    handler = new Handler(); 

      myProcessing(); 

    // This will cause the service to hang around 
    return (START_STICKY); 
} 


@Override 
public IBinder onBind(Intent intent) { 
    return (null); 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 

    } 
} 

super.onDestroy()の前に、上記のonDestroy()でさまざまなアクティビティを試してみました。私は以下を試しました:

 Intent i = new Intent(this, MyService.class); 
    stopService(i); 

MyServiceはただ実行し続けます。定義上、このサービスはシングルトンだと私は信じています。

+0

私はonDestroyを実装し、このイベント内のすべてのワーカースレッドを停止する必要があると思います! –

+0

試しonDestroy()まず、運がない。 –

答えて

2

あなたは、サービスクラスの中

1)stopselfを呼び出して、あなたがそれを行うことができる2つの方法は、()があるserivceを停止する場合。

2)stopService()を使用しています。

サービスクラスが異なるパッケージ(同じパッケージに入っていても)であれば、サービスにインテントフィルタを使用する方が良いと言います。サービスを停止して開始しやすくなります以下のように。

<service android:name=".services.MyService" android:enabled="true"> 
     <intent-filter android:label="@string/myService" > 
      <action android:name="custom.MY_SERVICE"/> 
     </intent-filter> 
    </service> 

あなたのサービス・クラスで
public static final String ServiceIntent = "custom.MY_SERVICE" 

これを追加して、あなたは以下のようなサービスを開始または停止することができます。

startService(new Intent(MyService.ServiceIntent)); 
stopService(new Intent((MyService.ServiceIntent)); 

希望です。ありがとう

+0

stopSelf()は機能しませんでしたが、インテントフィルタがどのように機能するかがわかります。 Tks。 –

+0

あなたはあなたのログを投稿できますか? – Jois

関連する問題