サーバーに1時間ごとに場所の更新を送信する長時間実行されるサービスを作成しました。ユーザーが現在地の更新を送信したくない場合は、アプリでオフにします。そのため、(最初のアクティビティで) サービスを開始しており、別のアクティビティから既に実行中のサービスを停止したいと考えていました。そのため、以下のようにマニフェスト ファイルで Service のアクションを宣言しました。
<service android:name=".services.LocationService" android:process=":bgservice">
<intent-filter >
<action android:name="com.example.STOP_LOC_SERVICE"/>
<action android:name="com.example.START_LOC_SERVICE"/>
</intent-filter>
</service>
ここでは、アプリ プロセスに関係なくサービスを実行したいので、:bgservice を指定して別のサービス名を取得しました。これは、私のサービスがリモート サービスであることを意味しますか。もしそうなら、これは以下の問題を引き起こします。
次に、以下のコードを使用して Service クラスでサービスを開始および停止します。
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if(intent.getAction().equals("com.example.STOP_LOC_SERVICE"))
{ // means that you have envoked action that will has to stop the service
LocationService.this.stopSelf();
}
else
{
return super.onStartCommand(intent, flags, startId);
}
return START_STICKY;
}
以下の行でサービスを開始するには
Intent istart = new Intent("com.example.START_LOC_SERVICE");
startService(istart);
線の下でサービスを停止するには
Intent istop = new Intent("com.example.STOP_LOC_SERVICE");
startService(istop);
ほとんどのデバイスですべてが正常に機能しています。さまざまな数のデバイスでサービスをテストしました。しかし最近、Service の OnStartCommand() で NullPointerException が発生しました。そのメソッドで null を見つけることができません。Intent が null であることを期待していますが、intent が null の場合、サービスを呼び出す方法。この問題は、すべてのデバイスで発生するわけではありません。
前もって感謝します。
エラーは onstartcommand の if ループにあります
ログキャット:
java.lang.RuntimeException: Unable to start service com.example.services.LocationService@410e5be8 with null: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2376)
at android.app.ActivityThread.access$1900(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.services.LocationService.onStartCommand(LocationService.java:53)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2359)
... 10 more