如何在 android 中添加和检索意图中的数据

How to add and retrieve data from an intent in android

我试图在 android 中实现推送通知,下面是我的 receiver 代码

public class MessageReceiver extends BroadcastReceiver {
    public void onReceive(Context ctx, Intent intent) {
        Intent myIntent = new Intent(ctx, MainActivity.class);
        myIntent.putExtra("skipList", true);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                ctx, 0, myIntent, 0);
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(ctx)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle(intent.getExtras().getString("subject"))
                        .setContentText(intent.getExtras().getString("cover"))
                        .setContentIntent(pendingIntent);
        mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        NotificationManager mNotificationManager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
    }
}

所以根据上面的代码,我将数据 skipList = True 添加到意图 myIntent

我只想在我的 MainActivity.java 文件中检索此数据,如下所示

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            Intent iin= getIntent();
            Log.v("<<<<<<<<<<<<iiiiiiiii>>>>>>>>>>>>>>>>",iin.toString());
            Bundle b = iin.getExtras();
            Log.v("<<<<<<<<<<<<bbbbbbbb>>>>>>>>>>>>>>>>",b.toString());
            String wow = b.getString("skipList");
            Log.v("<<<<<<<<<<<<wowowowoow>>>>>>>>>>>>>>>>",wow.toString());
}

但是我无法从意图中获取数据我做错了什么?

您正在使用带有布尔参数的 putExtra,但您将其作为字符串检索。 您需要使用 getBooleanExtra() 方法获取它。 只需替换这一行:

String wow = b.getString("skipList");

有了这个:

boolean wow = b.getBooleanExtra("skipList");

您正在 putExtra 中传递 boolean 并尝试将其作为字符串检索。

我认为 this 教程可能对您有帮助,可以帮助您了解更多有关使用 intent 可以做什么的知识

您传递的是布尔值,因此您应该将布尔值读作 使用以下代码

getIntent().getBooleanExtra("skipList", defaultValue);

这可能对你有帮助。

在代码中通过意图传递布尔数据,但将其作为字符串获取: 像这样尝试,

   boolean isSkipList = getIntent().getExtras().getBoolean("skipList");

(或)

替换下一行:

  String wow = b.getString("skiplist");

这一行:

  boolean wow = b.getBoolean("skiplist");

你应该写

 boolean wow = b.getBooleanExtras("skipList");

 myIntent.putExtra("skipList", "true");