当我在一个Activity
中点击按钮时,我的Service
被调用。如果在Service
正在运行时向左滑动Activity
,它会崩溃。我也尝试通过在清单文件中添加android:process=":remote"
来将其运行在单独的进程中,但结果还是一样。
@Override
public void onCreate(){
super.onCreate();
Log.d("Service", "Creating");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
@Override
public int onStartCommand (Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Log.d("Started", "Service");
type = intent.getIntExtra("Type",-1);
mode = intent.getIntExtra("Mode",-1);
rank = intent.getIntExtra("Rank", -1);
latitude = intent.getDoubleExtra("Lat", -1.0);
longitude = intent.getDoubleExtra("Long", -1.0);
startTime = intent.getLongExtra("Start", 0);
endTime = intent.getLongExtra("End", 0);
我收到的错误信息是:
java.lang.RuntimeException: Unable to start service com.routofy.routofytest.MyLocationService@374afe93 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2913)
at android.app.ActivityThread.access$2100(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at com.routofy.routofytest.MyLocationService.onStartCommand(MyLocationService.java:89)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2896)
at android.app.ActivityThread.access$2100(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
这是在
type = intent.getIntExtra("Type",-1);
处的null
指针。
我知道杀死应用程序就是杀死进程,此时传递给Service
的Intent
为null
。但是如何处理这种情况,即使Activity
被关闭,Intent
也被传递给了Service
?
我希望Service
完全独立于Activity
。并且我像这样运行它:Intent pickIntent = new Intent(getApplicationContext(),MyLocationService.class);