0

我的通知栏上有一条通知,它重定向到我的应用程序。这是我的做法。

private void sendNotificationToDevice(String message)
 {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        CharSequence tickerText = message;
        long when = System.currentTimeMillis();

        @SuppressWarnings("deprecation")
        Notification notification = new Notification(icon, tickerText, when);
        Context context = getApplicationContext();
        CharSequence contentTitle = "Landstar";
        CharSequence contentText = message;
        Intent intent= new Intent(context, Login.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,  PendingIntent.FLAG_UPDATE_CURRENT | Notification.FLAG_AUTO_CANCEL);
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_VIBRATE;


        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        mNotificationManager.notify(1111, notification);
 }

我想知道当用户单击通知栏上的通知时我可以在哪里处理事件。我不喜欢在 onResume 中处理它。我希望它与它分开。单击通知时的行为返回到我的应用程序。但不是我所期望的,当应用程序在后台时,我正在做后台处理。所以我希望我的应用程序在我单击通知时反映该过程。有任何想法吗?谢谢!

4

1 回答 1

0

此代码放在通知发送函数调用之后

Intent broadcastIntent = new Intent();
broadcastIntent.setAction("RECEIVED_ACTION");
broadcastIntent.putExtra("msg", message);
ctx.sendBroadcast(broadcastIntent);

使用广播接收器,您可以直接进入您的应用程序。

下面的代码是在您的活动中调用的。// BroadcastReceiver 必须覆盖 onReceive() 事件。私人广播接收器 gcmReceiver = 新的广播接收器() {

    private String broadcastMessage;

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

        broadcastMessage = intent.getExtras().getString("gcm");

        if (broadcastMessage != null && viewAdminLimit != null) {
            // display our received message

        }

    }
};

并在您的活动中调用以下方法

public void onResume() {

        IntentFilter gcmFilter = new IntentFilter();
        gcmFilter.addAction("RECEIVED_ACTION");
        viewAdminLimit.registerReceiver(gcmReceiver, gcmFilter);

    }

public void onPause() {

        viewAdminLimit.unregisterReceiver(gcmReceiver);

    }

我希望这段代码对你有用。

于 2013-09-12T07:26:38.117 回答