主活动无法从Firebase通知意图获取额外信息

9
我已经尝试了3天在Android通知中工作,当用户点击通知时,Activity打开。但每次我设置toast时,它都会显示为null。尝试了一些来自SOF的解决方案,但并没有起作用。您能否请看看代码有什么问题?提前感谢。
通知代码如下:
private void sendPushNotification(JSONObject json) {
    //optionally we can display the json into log
    int notificationId = new Random().nextInt();

    Log.e(TAG, "Notification JSON " + json.toString());
    try {
        //getting the json data
        JSONObject data = json.getJSONObject("data");

        //parsing json data
        String title = data.getString("title");
        String message = data.getString("message");
        String imageUrl = data.getString("image");

        // Instantiate a Builder object.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplicationContext(),"Default");

        Intent notifyIntent = new Intent(this, MainActivity.class);
        notifyIntent.putExtra("fromNotification", true);
        // Sets the Activity to start in a new, empty task
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        // Creates the PendingIntent
        PendingIntent pendingIntent =
                PendingIntent.getActivity(
                        this.getApplicationContext(), notificationId,
                        notifyIntent,
                        PendingIntent.FLAG_ONE_SHOT
                );

        //int id = 1;
        // Puts the PendingIntent into the notification builder
        builder.setContentIntent(pendingIntent);
        // Notifications are issued by sending them to the
        // NotificationManager system service.
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // Builds an anonymous Notification object from the builder, and
        // passes it to the NotificationManager
        if (mNotificationManager != null) {
            mNotificationManager.notify(notificationId, builder.build());
        }


    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

主活动(mainActivity.class)是

public class MainActivity extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setElevation(0);
    }

    // Open Tab
    if(getIntent().getExtras() != null){

        Bundle b = getIntent().getExtras();
        boolean cameFromNotification = b.getBoolean("fromNotification");

        Toast.makeText(this.getApplicationContext(),
                "Error: " + getIntent().getExtras(),
                Toast.LENGTH_LONG).show();

        viewPager = findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = findViewById(R.id.tabs);
        viewPager.setCurrentItem(1);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();

    }
    else {
        viewPager = findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = findViewById(R.id.tabs);
        viewPager.setCurrentItem(0);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();

    }



}



@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
} }

这些通知是来自服务器还是你试图从应用程序手动发送的? - AbhayBohra
请检查此链接...https://dev59.com/5pvga4cB1Zd3GeqP6LiX - Vikas singh
这是我的 PHP Web 服务器发送到 Firebase 的内容:'https://fcm.googleapis.com/fcm/send'。 - ian ajah
5个回答

5
如果您向意图添加了额外内容,但在接收活动中没有收到它们,可能有两个原因:
1. 活动已经存在于Android后台堆栈中,而额外的内容未在onCreate()中捕获,但可以在onNewIntent()中找到。
2. 如果使用PendingIntent传递额外的内容,则根据官方文档http://developer.android.com/reference/android/app/PendingIntent.html,必须确保每个意图在行动、数据、类型、类和类别方面都有差异。或者通过使用FLAG_CANCEL_CURRENT或FLAG_UPDATE_CURRENT取消系统中当前的PendingIntent来正确传递额外内容。

0

感谢大家,最终我通过遵循这篇帖子的方法使它工作了。

我之前只使用通知,但在禁用来自我的PHP服务器的通知并仅使用数据后,问题得到解决,我可以发送通知并且MainActivity可以从意图中捕获PutExtra。


0

0

将标志PendingIntent.FLAG_ONE_SHOT更改为PendingIntent.FLAG_UPDATE_CURRENT

PendingIntent pendingIntent =
            PendingIntent.getActivity(
                    this.getApplicationContext(), notificationId,
                    notifyIntent,
                    PendingIntent. FLAG_UPDATE_CURRENT
            );

如果我们使用意图附带信息,我们必须使用标志PendingIntent.FLAG_UPDATE_CURRENT调用PendingIntent.getActivity(),否则相同的附加信息将被重复使用于每个收到的通知。

1
已经按照在 SOF 上提到的方式尝试了 FLAG_UPDATE_CURRENT,但仍然无法正常工作。 - ian ajah

0
在扩展了BroadcastReceiver的BroadcastReceiver类中,在onReceive()方法中加入以下代码。
Intent intent2open = new Intent(context, YourActivity.class);
intent2open.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent2open.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
String name = "KEY";
String value = "String you want to pass";
intent2open.putExtra(name, value);
context.startActivity(intent2open);

FLAG_ACTIVITY_SINGLE_TOP 确保应用程序在已经打开的情况下不会重新打开。这意味着首次打开 YourActivity 的“旧”意图将被重复使用,它将不包含额外的值。您必须在 YourActivity 中的另一个方法 onNewIntent() 中捕获它们。

public class YourActivity extends Activity {
    private String memberFieldString;

    @Override
    public void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         // Code doing your thing...
    } // End of onCreate()

    @Override
    protected void onNewIntent(Intent intent) {
    Log.d("YourActivity", "onNewIntent is called!");

    memberFieldString = intent.getStringExtra("KEY");

    super.onNewIntent(intent);
} // End of onNewIntent(Intent intent)

    @Override
    protected void onResume() {
        if (memberFieldString != null) {
            if (opstartsIntent.getStringExtra(KEY) != null) {
               Log.d("YourActivity", "memberFieldString: "+ memberFieldString);
            } else {
               Log.d("YourActivity", "The intent that started YourActivity did not have an extra string value");
            }
        }
    } // End of onResume()

}  // End of YourActivity

请注意这两个if语句 - onResume()不能确定它是在OnCreate() -> OnStart() 还是 onRestart() -> onStart()之后被调用。

看起来他们没有使用BroadcastReceiver,而是使用getActivity()而不是getBroadcast()。根据这个链接:https://dev59.com/m2Yr5IYBdhLWcg3wYpQg#13716784,看起来应该可以工作。 - Daniel Nugent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接