0

我有通知,点击通知应该使用意图放置值。此值应在其他 Activity 的 BroadcastReceiver 中接收。任何帮助它如何修复?下面是我的代码:

public void showNotification(){
        Intent intent = new Intent(MainActivity.ACTION_NEW_MSG);
        intent.putExtra(MainActivity.MSG_FIELD, "TEST VALUES");
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        ComponentName cn = new ComponentName(getApplicationContext(), MainActivity.class);
        intent.setComponent(cn);
        sendBroadcast(intent);
        contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);


     notification = new NotificationCompat.Builder(getApplicationContext())
                    .setCategory(Notification.CATEGORY_PROMO)
                    .setContentTitle("TEST VALUE")
                    .setContentText("Please click for")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setAutoCancel(false)
                    .setVisibility(1)
                    .setSubText("Time left: " + millisUntilFinished/1000)
                    .addAction(android.R.drawable.ic_menu_view, "View details", contentIntent)
                    .setContentIntent(contentIntent)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setVibrate(new long[]{0}).build();
            notificationManager =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            int notification_id = 666;
            notificationManager.notify(notification_id, notification);
        }

在 MainActivity 下方:

    private void initReceiver() {
    myReceiver = new MyReceiver();
    IntentFilter filter = new IntentFilter(ACTION_NEW_MSG);
    registerReceiver(myReceiver, filter);
}

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_NEW_MSG)) {
            String message = intent.getStringExtra(MSG_FIELD);
            Toast.makeText(getApplicationContext(),message, Toast.LENGTH_LONG).show();
            Log.e("TESTING", "TESTING");
        }
    }
}
4

1 回答 1

0

你为什么不使用服务而不是接收者?您可以像这样创建意图:Intent i = new Intent(MainActivity.this, MyService.class); 您可以在意图中添加额外内容和操作。在 Service 类中,只需覆盖此函数:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        if (intent != null) {
            final String action = intent.getAction();
        }
    }
于 2015-11-04T18:46:07.440 回答