在AndroidManifest.xml中,我定义了以下组件
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.admin.freddyspeaks" />
</intent-filter>
</receiver>
<service
android:name="com.admin.services.NodeGcmListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name="com.admin.services.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<service
android:name="com.admin.services.RegistrationIntentService"
android:exported="false" />
NodeGcmListenerService.java
class NodeGcmListenerService extends GcmListenerService {
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d("", "From: " + from);
Log.d("", "Message: " + message);
//Set data
}
}
MyInstanceIDListenerService.java
public class MyInstanceIDListenerService extends InstanceIDListenerService {
@Override
public void onTokenRefresh() {
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
这是RegistrationIntentService.java
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
public RegistrationIntentService() {
super(TAG);
}
@Override
public void onHandleIntent(Intent intent) {
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
sendRegistrationToServer(token);
}
catch(IOException e) {
Log.e(TAG,"Unable to register device",e);
}
}
}
当我从服务器发送消息并且应用程序强制关闭时,不会调用NodeGcmListenerService onMessage方法
答案 0 :(得分:1)
当应用程序强行关闭时,GCMListenerService不会被调用
当应用程序被强制关闭时,它的字面意思是。没有正常的生命周期保证。您的应用程序行为不端,现在立即被击落。系统将清理剩余的,但你的代码无处可做。
PS:在崩溃后检查堆栈跟踪。