解析SDK实现定制的BroadcastReceiver在Android的推送通知 [英] Parse SDK implement custom BroadcastReceiver for push notifications in android

查看:213
本文介绍了解析SDK实现定制的BroadcastReceiver在Android的推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开始使用Android上的解析推送通知,但我无法找到任何方式来实现自己的BroadcastReceiver这将响应推送通知执行操作。

在他们的入门,他们给那里的接收器和意图的服务包含在JAR文件中的程序示例(和code不落实,这样我就可以尝试用它玩)。类似的问题已经在这里问,但它的两岁得到的答复有11 downvotes。

有一些其他的博客文章,例如如这里,但他们没有正常工作(一个在链接两岁)。

所以,请好心提示一步步的方式来实现相同的。

编辑:

我试过code。通过droidx的建议。但是,这是行不通的。我送我的Andr​​oidManifest.xml(在code其余是完全一样的,他建议):

 <?XML版本=1.0编码=UTF-8&GT?;
<清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.rahulserver.parsenotificationdemo>
    <使用许可权的android:NAME =android.permission.INTERNET对/>
    <使用许可权的android:NAME =android.permission.ACCESS_NETWORK_STATE/>
    <使用许可权的android:NAME =android.permission.WAKE_LOCK/>
    <使用许可权的android:NAME =android.permission.VIBRATE/>
    <使用许可权的android:NAME =android.permission.RECEIVE_BOOT_COMPLETED/>
    <使用许可权的android:NAME =android.permission.GET_ACCOUNTS/>
    <使用许可权的android:NAME =com.google.android.c2dm.permission.RECEIVE/>    <! -
      重要提示:在下面的线条变com.parse.starter.permission.C2D_MESSAGE
      以匹配您的应用程序的包名+.permission.C2D_MESSAGE。
     - >
    <许可安卓的ProtectionLevel =签名
        机器人:名字=com.rahulserver.parsenotificationdemo.permission.C2D_MESSAGE/>
    <使用许可权的android:NAME =com.rahulserver.parsenotificationdemo.permission.C2D_MESSAGE/>
    <应用
        机器人:名字=。ParseNotification
        机器人:allowBackup =真
        机器人:图标=@的mipmap / ic_launcher
        机器人:标签=@字符串/ APP_NAME
        机器人:主题=@风格/ AppTheme>
        <活动
            机器人:名字=。MainActivity
            机器人:标签=@字符串/ APP_NAME>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.MAIN/>                <类机器人:名字=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;
        <服务机器人:名字=com.parse.PushService/>
        <接收机器人:名字=com.parse.ParseBroadcastReceiver>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.BOOT_COMPLETED/>
                <作用机器人:名字=android.intent.action.USER_ preSENT/>
            &所述; /意图滤光器>
        < /接收器>
        <接收机器人:名字=。MyCustomParsePushReceiver
            机器人:出口=假>
            &所述;意图滤光器>
                <作用机器人:名字=com.parse.push.intent.RECEIVE/>
                <作用机器人:名字=com.parse.push.intent.DELETE/>
                <作用机器人:名字=com.parse.push.intent.OPEN/>
            &所述; /意图滤光器>
        < /接收器>
        <接收机器人:名字=com.parse.GcmBroadcastReceiver
            机器人:权限=com.google.android.c2dm.permission.SEND>
            &所述;意图滤光器>
                <作用机器人:名字=com.google.android.c2dm.intent.RECEIVE/>
                <作用机器人:名字=com.google.android.c2dm.intent.REGISTRATION/>                <! -
                  重要提示:改变com.parse.starter来匹配你的应用程序的包名称。
                 - >
                <类机器人:名字=com.rahulserver.parsenotificationdemo/>
            &所述; /意图滤光器>
        < /接收器>
    < /用途>< /清单>


解决方案

下面是一个例子!

 公共类ParseCustomBroadcastReceiver扩展ParsePushBroadcastReceiver {    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){
        尝试{            JSONObject的JSON =新的JSONObject(intent.getExtras()的getString(com.parse.Data)。);
            Log.d(TAG,json.getString(警报)的toString());            。最后弦乐notificationTitle = json.getString(题)的toString();
            。最后弦乐notificationContent = json.getString(提醒)的toString();
            最后弦乐URI = json.getString(URI);            意向resultIntent = NULL;
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(上下文);
                resultIntent =新意图(背景下,HomeScreen.class);
                stackBuilder.addParentStack(HomeScreen.class);            stackBuilder.addNextIntent(resultIntent);
            的PendingIntent resultPendingIntent =
                    stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
//自定义您的通知 - 样品code
            NotificationCompat.Builder建设者=
                    新NotificationCompat.Builder(上下文)
                            .setSmallIcon(R.mipmap.ic_notification_icon)
                            .setContentTitle(notificationTitle)
                            .setContentText(notificationContent);            INT mNotificationId = 001;
            NotificationManager mNotifyMgr =
                    (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotifyMgr.notify(mNotificationId,builder.build());
        }赶上(JSONException E){
            Log.d(TAG,e.getMessage());
        }    }
}

指导,接收器代替机器人的名字您的自定义路径的BroadcastReceiver

 <接收
            机器人:名字=。receivers.ParseCustomBroadcastReceiver
            机器人:出口=假>
            &所述;意图滤光器>
                <作用机器人:名字=com.parse.push.intent.RECEIVE/>
                <作用机器人:名字=com.parse.push.intent.DELETE/>
                <作用机器人:名字=com.parse.push.intent.OPEN/>
            &所述; /意图滤光器>
        < /接收器>

在您的应用程序类,确保已订阅推送解析像这样

  Parse.initialize(这一点,ParseUtils.PARSE_APPLICATION_ID_DEV,ParseUtils.PARSE_CLIENT_KEY_DEV);
        ParseObject.registerSubclass(Article.class);        ParsePush.subscribeInBackground(,新SaveCallback(){
            @覆盖
            公共无效完成(ParseException的E){
                如果(E == NULL){
                    Log.d(TAG,成功订阅广播频道。);
                }其他{
                    Log.e(TAG,未能认购推,E);
                }
            }
        });

更新:

以上广播接收预计从parse仪表盘发送一个JSON对象通常通知包含三个名称值对的:

  {警告:提示信息,称号:标题,URI:喇嘛喇嘛}

当你只使用普通字符串例如:世界,你好!在解析推的仪表板,内部它去,因为只有警示标签。像这样: {警告:世界你好!,标题为=空/,URI=空/}

广播接收器code上面没有这个null检查,所以它与例外抓不抓的标题/ URI。

所以,你可以根据你是从推送通知期待什么添加一些null检查。

事情是这样的:

  JSONObject的JSON =新的JSONObject(intent.getExtras()的getString(com.parse.Data)。);
            Log.d(TAG,json.getString(警报)的toString());            如果(json.has(标题)){
                 。notificationTitle = json.getString(题)的toString();
            }
            如果(json.has(警告)){
                 。notificationAlert = json.getString(提醒)的toString();
            }            如果(json.has(URI)){
                notificationURI = json.getString(URI);
            }

然后设置相应的 contentTitle contentText 在通知

  NotificationCompat.Builder建设者=
                    新NotificationCompat.Builder(上下文)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(notificationAlert)
                            .setContentText(notificationAlert);

希望这有助于!

I am trying to get started with Parse push notification on Android, but I could not find any way to implement my own BroadcastReceiver which would perform action in response to a push notification.

In their "getting started", they give a program sample where the receiver and the intent service is contained in the jar file (and not implemented in the code, so that I could try and play with it). A similar question has been asked here, but it's two years old and the answer has 11 downvotes.

There are a few other blog posts, e.g. as in here, but none of them work properly (the one in that link was two years old).

So please kindly suggest a step by step way to implement the same.

EDIT:

I tried the code as suggested by droidx. But it does not work. I am sending my AndroidManifest.xml (rest of the code is exactly as he suggested):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rahulserver.parsenotificationdemo" >
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <!--
      IMPORTANT: Change "com.parse.starter.permission.C2D_MESSAGE" in the lines below
      to match your app's package name + ".permission.C2D_MESSAGE".
    -->
    <permission android:protectionLevel="signature"
        android:name="com.rahulserver.parsenotificationdemo.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.rahulserver.parsenotificationdemo.permission.C2D_MESSAGE" />
    <application
        android:name=".ParseNotification"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.parse.PushService" />
        <receiver android:name="com.parse.ParseBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>
        <receiver android:name=".MyCustomParsePushReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="com.parse.push.intent.RECEIVE" />
                <action android:name="com.parse.push.intent.DELETE" />
                <action android:name="com.parse.push.intent.OPEN" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.parse.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" />

                <!--
                  IMPORTANT: Change "com.parse.starter" to match your app's package name.
                -->
                <category android:name="com.rahulserver.parsenotificationdemo" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

解决方案

Here's an example!

public class ParseCustomBroadcastReceiver extends ParsePushBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try {

            JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
            Log.d(TAG, json.getString("alert").toString());

            final String notificationTitle = json.getString("title").toString();
            final String notificationContent = json.getString("alert").toString();
            final String uri = json.getString("uri");             

            Intent resultIntent = null;
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);


                resultIntent = new Intent(context, HomeScreen.class);
                stackBuilder.addParentStack(HomeScreen.class);

            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent =
                    stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


//Customize your notification - sample code
            NotificationCompat.Builder builder =
                    new NotificationCompat.Builder(context)
                            .setSmallIcon(R.mipmap.ic_notification_icon)
                            .setContentTitle(notificationTitle)
                            .setContentText(notificationContent);

            int mNotificationId = 001;
            NotificationManager mNotifyMgr =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotifyMgr.notify(mNotificationId, builder.build());


        } catch (JSONException e) {
            Log.d(TAG, e.getMessage());
        }

    }
}

Following this guide, replace android name for the receiver to the path of your custom broadcastreceiver

<receiver
            android:name=".receivers.ParseCustomBroadcastReceiver"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.parse.push.intent.RECEIVE" />
                <action android:name="com.parse.push.intent.DELETE" />
                <action android:name="com.parse.push.intent.OPEN" />
            </intent-filter>
        </receiver>

In your application class, make sure to have subscribed to Parse Push like this

Parse.initialize(this, ParseUtils.PARSE_APPLICATION_ID_DEV, ParseUtils.PARSE_CLIENT_KEY_DEV);
        ParseObject.registerSubclass(Article.class);

        ParsePush.subscribeInBackground("", new SaveCallback() {
            @Override
            public void done(ParseException e) {
                if (e == null) {
                    Log.d(TAG, "successfully subscribed to the broadcast channel.");
                } else {
                    Log.e(TAG, "failed to subscribe for push", e);
                }
            }
        });

Update:

The above broadcast receiver expects to send a json object notification from parse dashboard usually consists of three name value pairs:

{ "alert": "Alert message", "title": "Title", "uri": "bla bla" } 

When you use only plain string for eg: hello world! in parse push dashboard, internally it goes as only alert tag. something like this : {"alert" : "hello world!, "title" = null/"", "uri" = null/""}

The broadcast receiver code above doesn't have this null checks, so it's caught in the catch with exception No title/uri.

So you can add some null checks based on what you are expecting from the push notification.

Something like this:

JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
            Log.d(TAG, json.getString("alert").toString());

            if (json.has("title")) {
                 notificationTitle = json.getString("title").toString();
            }
            if (json.has("alert")) {
                 notificationAlert = json.getString("alert").toString();
            }

            if(json.has("uri")) {
                notificationURI = json.getString("uri");
            }

Then set appropriate contentTitle and contentText in notification

 NotificationCompat.Builder builder =
                    new NotificationCompat.Builder(context)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(notificationAlert)
                            .setContentText(notificationAlert);

Hope this helps!

这篇关于解析SDK实现定制的BroadcastReceiver在Android的推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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