【问题标题】:Send data to activity when clicked on notification?单击通知时将数据发送到活动?
【发布时间】:2019-10-07 16:24:23
【问题描述】:

点击通知时我正在打开一个活动。通知是从服务类激活的。我想向从通知打开的新活动发送数据,我正在使用 intent1.putExtra("lable",lable);但在新活动中,它给了我空指针例外。

 intent1 = new Intent(this.getApplicationContext(), simplestop.class);
            intent1.putExtra("lable",lable);

PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0); 
Notification mNotify  = new Notification.Builder(this)
            .setContentTitle("title" + "!")
            .setContentText("Click me!")
            .setSmallIcon(R.drawable.ic_launcher_background)
                            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

【问题讨论】:

  • 将代码发布到您想要获得额外信息的地方。
  • 向我们展示您如何收到新活动的意向。
  • 显示您检索数据的活动代码
  • 显示如何检索数据。
  • 在其他活动中我正在使用此代码接收其他活动中的代码 lable = getIntent().getExtras().getString("lable");

标签: android android-intent notifications android-pendingintent


【解决方案1】:

我使用此代码向activity 发送数据。

Intent intent = new Intent(this, MainActivity.class)
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("from", "notification");
                    pIntent = PendingIntent.getActivity(this, 3, intent,
                            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

可能是您在设置flag=0 时遇到问题,或者尝试将请求code=0 更改为任何其他整数。

【讨论】:

    【解决方案2】:

    发送数据。

    Intent intent = new Intent(getApplicationContext(), simplestop.class);
    intent.putExtra("lable", lable);
    
    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    final RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.yourLayoutOfNotification);
    contentView.setOnClickPendingIntent(R.id.IdOfTheItemYouClick, contentIntent);
    

    尝试在您的 simplestop.class 中检索类似这样的数据

    if (getIntent().getDataString() == null) {
       String lable = Objects.requireNonNull(getIntent().getExtras()).getString("lable");
     }
    

    我认为你需要拨打onNewIntentsimplestop.class 并在那里检索数据。

    如果检索到数据,请尝试创建Log

    Log.d("Data", lable);
    

    并告诉Log 显示的是什么。

    【讨论】:

    • 我已经尝试过了,但它不起作用。我认为问题是发送数据
    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多