从Android Wear中的BroadcastReceiver调用IntentService

时间:2014-07-12 18:14:57

标签: android wear-os

是否可以在Android服装中从广播接收器启动服务?我能够从活动开始服务。

我尝试过同样的事情:

Intent i = new Intent(context, ServiceToSendData.class);
context.startService(i);

我收到以下错误:

     java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.SCREEN_OFF flg=0x50000010 } in com.ysz.demo.ScreenDetectionReceiver@b3d20fc0
        at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:769)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5026)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at android.content.ComponentName.<init>(ComponentName.java:77)
        at android.content.Intent.<init>(Intent.java:3848)
       at com.ysz.demo.ScreenDetectionReceiver.trigger(ScreenDetectionReceiver.java:68)
       at      com.ysz.demo.ScreenDetectionReceiver.checktimeandsendtoshake(ScreenDetectionReceiver.java:60)  at com.ysz.demo.ScreenDetectionReceiver.onReceive(ScreenDetectionReceiver.java:41)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:759)

1 个答案:

答案 0 :(得分:1)

查看调用堆栈,此异常的唯一可能解释是context为空。

Intent i = new Intent(context, ServiceToSendData.class);

...

public Intent(Context packageContext, Class<?> cls) {
    mComponent = new ComponentName(packageContext, cls);  // <- Line 3848
}

...

public ComponentName(Context pkg, Class<?> cls) {
    mPackage = pkg.getPackageName();  // <- Line 77
    mClass = cls.getName();
}

是这样的吗?