当应用程序未打开时未发送GCM消息? [英] GCM Message is not sent when the app is not open?

查看:65
本文介绍了当应用程序未打开时未发送GCM消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我在我的应用程序上实现了GCM。我遵循本网站的教程代码

http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/



但是,这种行为很奇怪,例如

如果我杀了应用程序,那么当我发送通知时,它会不会立即在通知栏上显示,但只有当用户再次打开该应用程序时,例如,如果我在杀应用程序时发送两个通知,则仅当我打开该应用程序时才会收到两个通知。



这是GCM的行为吗?正如我预料它应该是什么样的whatsapp(即使我没有打开应用程序,该设备应该仍然收到通知和显示)



这是我的代码。感谢您的帮助



GcmBroadcastReceiver

  public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context,Intent intent){
ComponentName comp = new ComponentName(context.getPackageName(),
GCMNotificationIntentService.class.getName());
startWakefulService(context,(intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}

GCMNotificationIntentService

  public class GCMNotificationIntentService extends IntentService {

public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder构建器;

public GCMNotificationIntentService(){
super(GcmIntentService);
}

public static final String TAG =GCMNotificationIntentService;

@Override
protected void onHandleIntent(Intent intent){
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

字符串messageType = gcm.getMessageType(intent);
$ b $ if(!extras.isEmpty()){
if(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)){
sendNotification(Send error:+ extras.toString( ));
} else if(GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)){
sendNotification(服务器上的已删除邮件:+ extras.toString());
} else if(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)){

for(int i = 0; i <3; i ++){
Log.i(TAG ,Working ...+(i + 1)+/ 5 @+ SystemClock.elapsedRealtime());
尝试{
Thread.sleep(5000);
} catch(InterruptedException e){
}
}

Log.i(TAG,Completed work @+ SystemClock.elapsedRealtime());
sendNotification(getResources()。getString(R.string.gcm_news_remind));
Log.i(TAG,Received:+ extras.toString());
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);


private void sendNotification(String msg){
Log.d(TAG,准备发送通知...:+ msg);
mNotificationManager =(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);

PendingIntent contentIntent = PendingIntent.getActivity(this,0,new Intent(this,SplashScreen.class),0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getResources()。getString(R.string。 app_name))
.setStyle(new NotificationCompat.BigTextStyle()。bigText(msg))
.setContentText(msg);

mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID,mBuilder.build());
Log.d(TAG,通知发送成功。);


清单

 < manifest xmlns:android =http://schemas.android.com/apk/res/android
package =com.example.oshpedia
android:versionCode =1
android:versionName =1.0>

<使用权限android:name =android.permission.INTERNET/>
< uses-permission android:name =android.permission.ACCESS_NETWORK_STATE/>
<使用权限android:name =android.permission.GET_ACCOUNTS/>
<使用权限android:name =android.permission.WAKE_LOCK/>
< uses-permission android:name =com.example.oshpedia.permission.C2D_MESSAGE/>
< uses-permission android:name =com.google.android.c2dm.permission.RECEIVE/>
< uses-permission android:name =android.permission.ACCESS_NETWORK_STATE/>
< uses-permission android:name =android.permission.VIBRATE/>

< permission
android:name =com.example.oshpedia.permission.C2D_MESSAGE
android:protectionLevel =signature/>

< uses-sdk
android:minSdkVersion =9
android:targetSdkVersion =19/>

应用
android:name =。Defination.MyApp
android:allowBackup =true
android:icon =@ drawable / ic_launcher
android:label =@ string / app_name
android:largeHeap =true
android:theme =@ style / AppTheme>
< activity
android:name =。Activity.SplashScreen
android:label =@ string / app_name
android:theme =@ android:style / Theme .NoTitleBar.Fullscreen>
< intent-filter>

< category android:name =android.intent.category.LAUNCHER/>
< / intent-filter>
< / activity>
android:name =。Activity.Main
android:screenOrientation =portrait
android:windowSoftInputMode =stateHidden | adjustPan>
< / activity>
< activity
android:name =。Activity.AboutUs
android:screenOrientation =portrait>
< / activity>
< activity
android:name =。Activity.AboutApp
android:screenOrientation =portrait>
< / activity>
< activity
android:name =。Activity.Disclaimer
android:screenOrientation =portrait>
< / activity>
< activity
android:name =。Activity.EnquiryForm
android:screenOrientation =portrait
android:windowSoftInputMode =stateHidden | adjustPan>
< / activity>
< activity
android:name =。Activity.NewsDetail
android:screenOrientation =portrait>
< / activity>
< activity
android:name =。Activity.EnquiryDetail
android:screenOrientation =portrait>
< / activity>
< activity
android:name =。Activity.SearchResult
android:screenOrientation =portrait>
< / activity>
< activity
android:name =。Activity.LawDetail
android:screenOrientation =portrait>
< / activity>
< activity
android:name =。Activity.AdvanceSearch
android:screenOrientation =portrait>
< / activity>
< activity
android:name =。Activity.VideoChannel
android:screenOrientation =portrait>
< / activity>
< activity android:name =。Activity.VideoViewer>
< / activity>

< receiver
android:name =。GCM.GcmBroadcastReceiver
android:permission =com.google.android.c2dm.permission.SEND>
< intent-filter>

< category android:name =com.example.oshpedia/>
< / intent-filter>
< / receiver>

< service android:name =。GCM.GCMNotificationIntentService/>
< / application>

< / manifest>


解决方案

WhatsApp不完全依赖GCM m不知道它是否依赖于GCM)。如果您打开Android设备的设置并转到应用程序,然后运行服务(如果您使用的是不同于我使用的Android版本的2.3.6版本,菜单可能会有所不同),您会看到有一个WhatsApp服务在后台运行(假设您安装了WhatsApp)。如果您停止该服务,您将停止从WhatsApp接收消息,直到您再次启动该应用程序为止。



只要您不杀死,您的应用程序就可以接受GCM广播它明确。一旦你杀了它,它将不会收到任何广播,直到你下一次启动它(根据我读到的,自从Android 3.x以来就是这种情况)。但是,如果您将应用移至后台(例如启动其他应用或点击后退按钮,直至移至主屏幕或其他应用),则您的应用仍会收到来自GCM的消息。


Recently I implement the GCM on my app. I followed the tutorial code at this website

http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/

However, the behavior is quite strange , for example

If I kill the app, then when I send the notification, it will not show on the notification bar immediately , but only when the user open the app again, say, if I send two notification when I kill app, I receive two notification only when I open the app.

Is it the behavior of GCM? As I expect it should be something like the whatsapp (even I did not open app, the device should still receive the notification and display)

here is my code. Thanks for helping

GcmBroadcastReceiver

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(),
                GCMNotificationIntentService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

GCMNotificationIntentService

public class GCMNotificationIntentService extends IntentService {

    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;

    public GCMNotificationIntentService() {
        super("GcmIntentService");
    }

    public static final String TAG = "GCMNotificationIntentService";

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

                for (int i = 0; i < 3; i++) {
                    Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }

                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                sendNotification(getResources().getString(R.string.gcm_news_remind));
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    private void sendNotification(String msg) {
        Log.d(TAG, "Preparing to send notification...: " + msg);
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SplashScreen.class), 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        Log.d(TAG, "Notification sent successfully.");
    }
}

Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.oshpedia"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.example.oshpedia.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <permission
        android:name="com.example.oshpedia.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="19" />

    <application
        android:name=".Defination.MyApp"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Activity.SplashScreen"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Activity.Main"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|adjustPan" >
        </activity>
        <activity
            android:name=".Activity.AboutUs"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".Activity.AboutApp"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".Activity.Disclaimer"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".Activity.EnquiryForm"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|adjustPan" >
        </activity>
        <activity
            android:name=".Activity.NewsDetail"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".Activity.EnquiryDetail"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".Activity.SearchResult"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".Activity.LawDetail"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".Activity.AdvanceSearch"
            android:screenOrientation="portrait" >
        </activity>
        <activity
            android:name=".Activity.VideoChannel"
            android:screenOrientation="portrait" >
        </activity>
        <activity android:name=".Activity.VideoViewer" >
        </activity>

        <receiver
            android:name=".GCM.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.example.oshpedia" />
            </intent-filter>
        </receiver>

        <service android:name=".GCM.GCMNotificationIntentService" />
    </application>

</manifest>

解决方案

WhatsApp doesn't rely entirely on GCM (I'm not sure if it relies on GCM at all). If you open your Android device's Settings and go to Applications and then Running services (the menus may be a little different if you are using a different Android version than I'm using, which is 2.3.6), you'll see there's a WhatsApp service running in the background (assuming you have WhatsApp installed). If you stop that service, you would stop receiving messages from WhatsApp until you launch that app again.

Your app can accept GCM broadcasts only as long as you don't kill it explicitly. Once you kill it, it won't receive any broadcasts until the next time you launch it (according to what I read, that has been the case since Android 3.x). If, however, you move your app to the background (for example by launching another app or hitting the back button until you move to the home screen or to another app), your app would still get messages from GCM.

这篇关于当应用程序未打开时未发送GCM消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆