`

[Android]接收Push Notification及弹出Dialog

阅读更多

1、使用一个service接收gcm

public class MyGcmListenerService extends GcmListenerService {

    private static final String TAG = "MyGcmListenerService";


    /**
     * Called when message is received.
     *
     * @param from SenderID of the sender.
     * @param data Data bundle containing message data as key/value pairs.
     *             For Set of keys use data.keySet().
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        Log.d(TAG, "From: " + from);
        Log.d(TAG, "Message: " + message);

        for (String key : data.keySet() ) {
            Log.d(TAG, "key : " + key);
        }

        String messageId = data.getString("google.message_id");
        String messageKey = data.getString("message");
        String collapse_key = data.getString("collapse_key");
        String score = data.getString("score");

        String payload = data.getString("data.payload");
        String extraMap = data.getString("data.extraMap");

        Log.d(TAG, "Message id : " + messageId);
        Log.d(TAG, "message_key : " + messageKey + ",collapse_key : " + collapse_key + ",payload : " + payload
                + ",extraMap : " + extraMap);

        if (message == null || message.equals("")) {
            Log.d(TAG, "Received message from GCM not success...");
        } else {

            Log.d(TAG, "success received from GCM : " + message);


        }

        if (from.startsWith("/topics/")) {
            // message received from some topic.
            Log.d(TAG, "message received from some topic.");
        } else {
            // normal downstream message.
            Log.d(TAG, "normal downstream message.");

        }

        // [START_EXCLUDE]
        /**
         * Production applications would usually process the message here.
         * Eg: - Syncing with server.
         *     - Store message in local database.
         *     - Update UI.
         */

        /**
         * In some cases it may be useful to show a notification indicating to the user
         * that a message was received.
         */
        sendNotification(message,score);

        // [END_EXCLUDE]

    }

。。。。。。

 

2.建立推送(两个功能部分:1.点击Notification跳转AlertDialog 2.在MainActivity中弹框(使用LocalBroadcast)

private void sendNotification(String title,String content) {
        Intent intent = new Intent(this, AlertActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("title",title);
        bundle.putString("content",content);
        intent.putExtra("alert_gcm", bundle);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//PendingIntent 是点击推送后打开的Activity,第三个参数Intent可以设定跳转
//这里是跳转到一个自定义的AlertActivity中,里面打开AlertDialog(可以把Activity底色设为透明)
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle(title)
                .setContentText(content)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

        //MainActivity to received gcm notification
        Intent gcmComplete = new Intent(QuickstartPreferences.GCM_COMPLETE);

        Log.d(TAG, "title : " + title + " content : " + content);

        gcmComplete.putExtra("gcmBundle", bundle);
        LocalBroadcastManager.getInstance(this).sendBroadcast(gcmComplete);

    }
若点击Notification传值失败,一般调节一个flag的值:
flags有四个取值:
int FLAG_CANCEL_CURRENT:如果该PendingIntent已经存在,则在生成新的之前取消当前的。
int FLAG_NO_CREATE:如果该PendingIntent不存在,直接返回null而不是创建一个PendingIntent.
int FLAG_ONE_SHOT:该PendingIntent只能用一次,在send()方法执行后,自动取消。
int FLAG_UPDATE_CURRENT:如果该PendingIntent已经存在,则用新传入的Intent更新当前的数据。

我们需要把最后一个参数改为PendingIntent.FLAG_UPDATE_CURRENT,这样在启动的Activity里就可以用接收Intent传送数据的方法正常接收。

 

3.MainActivity建立接收器:

mGcmNotificationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Bundle bundle = intent.getBundleExtra("gcmBundle");
                String title = bundle.getString("title");
                String content = bundle.getString("content");
                Log.d(TAG, "title : " + title + " content : " + content);
                //Dialog to show content
                new AlertDialog.Builder(MainActivity.this,R.style.dialogTheme)
                        .setTitle(title)
                        .setMessage(content)
                        .setNegativeButton("OK", null)
                        .show();
            }
        };

 

注册接收器:

private void registerReceiver(){
 
        if (!isReceiverGcm){
            LocalBroadcastManager.getInstance(this).registerReceiver(mGcmNotificationBroadcastReceiver,
                    new IntentFilter(QuickstartPreferences.GCM_COMPLETE));
            isReceiverGcm = true;
        }
    }

 

@Override
    protected void onResume() {
        super.onResume();
        registerReceiver();

    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mGcmNotificationBroadcastReceiver);
        isReceiverGcm = false;
        super.onPause();
    }

 

4.AlertActivity:

Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("alert_gcm");
        String title = bundle.getString("title");
        String content = bundle.getString("content");
        Log.d(TAG, "title : " + title + " content : " + content);
        //Dialog to show content
        new AlertDialog.Builder(this,R.style.dialogTheme)
                .setTitle(title)
                .setMessage(content)
                .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(AlertActivity.this, MainActivity.class);
                        startActivity(i);
                    }
                })
                .show();

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics