从移动设备停止观看前台服务时出错

时间:2016-01-26 07:34:49

标签: android wear-os

从我的手机中我在Android手表中启动前台服务。我能够正确地做到这一点。但是当我尝试停止服务以及观看活动时,我收到一条错误消息(监视应用程序正在崩溃)。我正在使用消息监听器服务从移动设备接收消息。

我在手表应用程序中也有一个完全正常运行的停止按钮(如果我尝试从手表本身停止服务)并且它具有相同的代码行。当我从移动应用程序收到停止前台服务的消息时,我不确定我的错误。

@Override public void onMessageReceived(MessageEvent messageEvent) {

    Log.i(INFOTAG, "Stop msg received");

    if(messageEvent.getPath().equals(STOP_MESSAGE_PATH_2)){

        started = false;

        Intent stopIntent = new Intent(
                MainActivity.this, ForegroundService.class);
        stopService(stopIntent);

        this.finish();

    }
}

以下是我收到的错误日志:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.content.ComponentName.(ComponentName.java:77)
at android.content.Intent.(Intent.java:4160)
at com.magi.magidemo.MainActivity.onMessageReceived(MainActivity.java:464)
at com.google.android.gms.wearable.internal.zzcf$5.zza(Unknown Source)
at com.google.android.gms.wearable.internal.zzcf$5.zzs(Unknown Source)
at com.google.android.gms.internal.zzmn.zzb(Unknown Source)
at com.google.android.gms.internal.zzmn$zza.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

1 个答案:

答案 0 :(得分:0)

您需要从覆盖方法中获取Activity的实例。

像这样:

public MainActivity activity;

// in the override method

this.activity = activity;

然后使用它:

Intent stopIntent = new Intent(
            activity, ForegroundService.class);

看看:android.content.Context.getPackageName()' on a null object reference