2016-07-21 29 views
0

こんにちは私は、フォアグラウンドサービスとしてIntentServiceを立ち上げる際に問題があります。不幸にも、公式チュートリアルでは、メソッドのいくつかが存在しない場合、いくつかは推奨されなくなり、コードをどこに置くべきか、それらが提供する場所については言及されていないため、フォアグラウンドのAndroid IntentService

自分のIntentServiceを作成しましたが、onCreateメソッドをオーバーライドしました。それは次のように見えます:

私はそれがデバッグサイトではないことは知っていますが、確かに、私は行方不明です。 Settingsクラスは私のActivityクラスで、そこからstartServiceが呼び出されました。通知に必要なものをすべて設定し、最初の引数が0以外のstartForegroundを呼び出しました。まだ通知は表示されませんが、私はかなり確信していますが、そのサービスはバックグラウンドで動作しています。

任意の助けをいただければ幸いです(ところで。私はすでになく、無助けを借りて、前景のSO wothサービス上のさまざまなトピックで検索しました。)

+0

フォアグラウンドで使用した場合の使用例は? – apelsoczi

+0

アプリ:あなたはいくつかの設定を設定します。電話番号。設定アクティビティから起動ボタンを押すと、サービスが開始され、いくつかのイベントが待ち受けられます。イベントが発生した場合、サービスが電話をかけます(電話機が動いたときなどに便利ですが、私はユーザーに通知されたい、そのサービスがアクティブであることを望みます。設定アクティビティからサービスを無効にすることができます。 – DawidPi

+0

onHandleIntent()が完了した直後にIntentServiceが破棄されるため、おそらくIntentServiceは必要ありません。 – ianhanniballake

答えて

1

あなたがService代わりのIntentServiceを使用する場合は、コードを置くことができますあなたはそれがを返すそうでない場合は殺されたときにサービスを再作成することにしたいいけない場合START_NOT_STICKYを返し、onStartCommandで、

public class SettingsService extends Service { 

    private final IBinder mBinder = new LocalBinder(); 

    public class LocalBinder extends Binder { 
     public SettingsService getService() { 
      return SettingsService.this; 
     } 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     stopForeground(true); 
    } 

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

     Intent notificationIntent = new Intent(this, SettingsService.class); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
     Notification notification = new Notification.Builder(this) 
       .setContentTitle("myService") 
       .setContentText("this is an example") 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setOngoing(true) 
       .setContentIntent(pendingIntent) 
       .build(); 

     startForeground(101, notification); 

     return START_STICKY; 
    } 

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

    @Override 
    public boolean onUnbind(Intent intent) { 
     return super.onUnbind(intent); 
    } 
} 

Additionnaly:あなたは、通知& startForeground()onStartCommand内を構築するために書きました

関連する問題