应用程序未打开时,GCM 消息未发送?

2024-03-25

最近我在我的应用程序上实现了 GCM。我按照这个网站上的教程代码进行操作

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

然而,行为很奇怪,例如

如果我杀死应用程序,那么当我发送通知时,它不会立即显示在通知栏上,而是仅在用户再次打开应用程序时显示,也就是说,如果我在杀死应用程序时发送两个通知,我只会收到两个通知当我打开应用程序时。

这是GCM的行为吗?正如我所期望的,它应该类似于whatsapp(即使我没有打开应用程序,设备仍然应该收到通知并显示)

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

Gcm广播接收器

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 并不完全依赖于 GCM(我不确定它是否完全依赖于 GCM)。如果您打开 Android 设备的“设置”并转到“应用程序”,然后转到“运行服务”(如果您使用的 Android 版本与我使用的 Android 版本不同,即 2.3.6,则菜单可能会略有不同),您会看到有一个WhatsApp 服务在后台运行(假设您安装了 WhatsApp)。如果您停止该服务,您将停止接收来自 WhatsApp 的消息,直到您再次启动该应用程序。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

应用程序未打开时,GCM 消息未发送? 的相关文章

  • 尽管已被销毁,但多次打开子活动仍会导致 InstanceCountViolation

    我正在开发一个具有较低级别活动的项目 称为RecordView显示记录详细信息 例如图像 拍摄日期和时间以及纬度 经度信息 我不是尝试操纵相机进行地理标记并访问 exif 数据 而是尝试实现一个位置侦听器来获取首次拍摄图像的位置 按下按钮时
  • 从SQLite列中获取所有数字字符串并进行总和计算

    我是 Android 和 SQLite 的新手 我在 SQLite 中有一个只有数字的 AMOUNT 列 我可以在 ListView 中显示它 但我无法找到任何我理解的方法来将它们全部添加并显示在 TextView 中 这是数据库助手 im
  • 您的手机中未安装应用程序

    我在模拟器中运行该应用程序 它成功运行 并且应用程序的图标显示在模拟器菜单中 但是当我尝试从模拟器菜单再次运行该应用程序时 它不允许我从中运行并显示 Toast 您的手机中未安装应用程序 在图像中 红色圆形是我的应用程序图标 如果您有您的M
  • FCM:无法实例化接收器 com.google.firebase.iid.FirebaseInstanceIdReceiver:

    仅在 Oreo 8 0 中接收推送通知时应用程序崩溃 java lang RuntimeException Unable to instantiate receiver com google firebase iid FirebaseIns
  • 使用 Android NDK r5b 链接静态库时出现问题 [重复]

    这个问题在这里已经有答案了 最近升级到 NDK r5b 构建失败 并出现对静态库中函数的 未定义引用 这是错误 home brian workspace VoiceEngineDemo obj local armeabi v7a objs
  • 错误:链接引用失败。 -> 排队作业

    我正在使用 Kotlin 学习 Android Material Design 一切都很顺利 直到我尝试使用 android support design widget FloatingActionButton 当我重建项目时 我收到以下错
  • onScale 和 Canvas - 缩放图像后如何调整原点?

    我有一个非常简单的测试应用程序 带有自定义组件MyView java https github com afarber android newbie blob master TestScroll src de afarber testscr
  • Android 无法查找支持版本 27.0.0 的窗口

    更新后supportVersion to 27 0 0仅在 Android 5 0 2 上 应用程序会因以下堆栈跟踪而崩溃 W WindowManager Failed looking up window java lang Illegal
  • 如何从android中的webview获取选定的文本?

    我需要从网络视图中获取选定的文本 为此 我这样说 webView loadUrl javascript Android getHtml window getSelection toString 在我的触摸事件中 触摸事件效果很好 Andro
  • 如何将音频 Mediastore 持续时间转换为分钟和秒?

    我正在使用音频播放器教程androidhive info https www androidhive info 2012 03 android building audio player tutorial 在 SongsManager ja
  • 每当调用 startactivityforresult 时 Android 就会终止我的应用程序

    好吧 在我的应用程序中 我使用 Android 的默认相机和图库 startActivityforResult 为 Intent i new Intent android intent action PICK MediaStore Imag
  • 如何在android 4.2中显示选项菜单

    我正在尝试在我的测试应用程序中创建菜单选项 当我将清单中的主题设置为默认时 我可以看到菜单 菜单显示在顶部 如果我将清单中的主题设置为 NoTitleBar 我看不到菜单选项 我想在清单中设置主题 NoTitleBar 时获取菜单 如何修复
  • 小米设备正在停止前台服务

    我们有一个几乎永远运行的应用程序前台服务 同时使用系统托盘上的通知 这是正常的初始化 该应用程序仅依赖于此服务 在我们测试的每台设备上 即使任务被删除 服务也会继续运行 但在小米设备上 从最近的任务滑动后 它突然停止 然后再次启动 具体取决
  • 如何以编程方式启用小米应用程序的自动启动

    我想知道小米是否可以提供任何应用程序的后台服务 我的应用程序中有需要始终在后台运行的服务 在除小米之外的所有设备中都工作正常 如何以编程方式完成 也适用于小米 oppo vivo 和 oneplus 手机 try Intent intent
  • 如何为移动应用程序创建无密码登录

    我有兴趣在移动应用程序和 API 之间构建某种无密码登录 假设我可以控制两者 动机是必须登录对用户来说非常烦人并且存在安全风险 例如 用户将重复使用现有密码 我希望用户能够立即开始使用该应用程序 我想知道是否有一些可行的技术 例如 在移动设
  • Android 4.2以下如何设置layoutDirection为RTL

    尝试将布局元素设置为 RTL 顺序 4 2 及以上行 layoutDirection rtl 并在清单中 android supportsRtl true 工作得很好 但对于 4 2 以下则不然 解决方案有人吗 只需使用视图兼容使用 and
  • 是否可以用 C# 为 Android 编写应用程序?

    我们都知道Android运行Dalvik VM程序 通常开发人员用 Java 编写程序并将其编译为 Dalvik 字节码 我想知道是否有可能创建一个可以接受 C 代码并将其编译为 Dalvik 字节码的编译器 嗯 这是一种选择 或者您可以在
  • Android 上的 Facebook 深度链接

    我正在尝试在我的应用程序上实现 Facebook 的深度链接功能 并遇到了以下情况 我有一个名为 MainActivity 的活动 其声明如下
  • Android PhoneGap 中的自定义字体

    我尝试为我的应用程序制作自定义字体 为此 我在 html 文件中编写了以下代码 在我的 HTML 正文中
  • 在应用程序的所有活动中重用操作栏

    我创建了一个 MenuActivity 它有一个操作栏和一个拆分操作栏 我想将此操作栏和 splitactionbar 视图用于我的应用程序中的所有活动 我是 android 的新手 所以有人可以逐步指导我 另外 我试图将搜索图标放在操作栏

随机推荐