Android通知无法访问收到的字符串

时间:2016-07-25 11:30:23

标签: java android broadcastreceiver

我在MainActivity.java收到广播接收器中的通知。我需要为其他类访问此字符串textMessage -

if (intent.getAction().equals("NOTIFY_TEXT_MESSAGE")){
                String textMessage = intent.getStringExtra("TextMessage");
                Intent noti_intent = new Intent(MainActivity.this, NotificationReceiver.class);
                noti_intent.setAction("NotificationReceived");
                noti_intent.putExtra("NotificationMessage",textMessage);

                PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, noti_intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder builder =
                        new NotificationCompat.Builder(MainActivity.this)
                                .setSmallIcon(R.drawable.text_messages)
                                .setContentTitle(getResources().getString(R.string.Message_Title))
                                .setContentText(textMessage)
                                .setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
                                .setPriority(NotificationCompat.PRIORITY_HIGH) //must give priority to High, Max which will considered as heads-up notification
                                .addAction(0,
                                        getString(R.string.Open), pi)
                                .setAutoCancel(true);
                builder.setSound(soundUri);
                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(0, builder.build());
            }

在NotificationReceiver.class中,

public class NotificationReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if("NotificationReceived".equals(action)) {
            String msg = MainActivity.NotificationMessage;
            Log.v("shuffTest","msg" + msg);
        }
    }
}

在我的清单中,

<receiver android:name="com.example.NotificationReceiver">
            <intent-filter>
                <action android:name="NotificationReceived" />
            </intent-filter>
        </receiver>

为什么日志msg没有出现。我的代码中有什么错误?

1 个答案:

答案 0 :(得分:1)

尝试从意图中获取消息,如下所示:

public class NotificationReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if("NotificationReceived".equals(action)) {
            String msg = intent.getStringExtra("NotificationMessage");
            Log.v("shuffTest","msg" + msg);
        }
    }
}