我制作了一个使用 Android Cloud to Device Messaging 的应用程序,因为我使用这个应用程序从正确的图标启动它,所以它工作正常。我发现的问题是在设备本身启动之后。启动后,接收器正确启动并正确启动我想要使用的服务,检查它是否正在运行以执行某些任务并最终启动另一个服务。
为了实现它,我这样做了:
在清单上:
<receiver android:name=".C2DMReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<!-- Receive the actual message -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.myapp.app" />
</intent-filter>
<!-- Receive the registration id -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.myapp.app" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="com.myapp.app" />
</intent-filter>
</receiver>
在我的接收器中:
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent NewIntent = new Intent(context, MyService.class);
context.startService(NewIntent);
Log.i("C2DMReceiver", "MyService started");
}
然后 onMessage 接收接收者必须检查 MyService 是否正在运行。为此,我在 MyService 中编写:
// Use activity in C2DMReceiver class
public static Service getCurrentService() {
return curService;
}
所以要检查接收器,我这样做:
if (MyService.getCurrentService != null){
//DO ELSE
}
问题是这个布尔条件总是错误的,即使服务真的在运行。
为什么?