9

I have tried these 3 days working on android notification where user tap on notification then Activity open. But each time i set toast, it says null. Tried with some solutions from SOF, but doesn't work. can you please look what is wrong with the code? Thanks in advance.

The Notification code is

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());
    }
}

And mainActivity.class is

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);
} }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
ian ajah
  • 91
  • 1
  • 6

5 Answers5

5

If you have put extras to an intent and they are not received at the receiving activity, there could be 2 reasons..

  1. The activity already exists in android backstack and the extras are not caught in onCreate() but they can be found in onNewIntent()

  2. If the extras are passed with an activity of a PendingIntent, then as per the official documentation. http://developer.android.com/reference/android/app/PendingIntent.html. So, to pass the extras correctly, either you need to make sure each of the intents are having differentiation in terms of action, data, type, class, and categories. Or cancel the current PendingIntent if exists in the system by using FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT.

Hasif Seyd
  • 1,686
  • 12
  • 19
0

Change the flag PendingIntent.FLAG_ONE_SHOT to PendingIntent.FLAG_UPDATE_CURRENT

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

If we use intent extras, we have to call PendingIntent.getActivity() with the flag PendingIntent.FLAG_UPDATE_CURRENT, otherwise the same extras will be reused for every notification recieved.

Basil jose
  • 774
  • 3
  • 11
0

In the BroadcastReceiver class that extends BroadcastReceiver. Put in the following code in 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);

The FLAG_ACTIVITY_SINGLE_TOP makes sure the apps doesn't re-open if already open. This means that the "old" intent that opened YourActivity in the first place is re-used and it will NOT contain the extra values. You have to catch them in another method called onNewIntent() in YourActivity.

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

Please note the two if statements - the onResume() does not know if it's called after OnCreate()->OnStart() OR onRestart()->onStart()

Dilip
  • 2,622
  • 1
  • 20
  • 27
  • Looks like they are not using a BroadcastReceiver, using `getActivity()` rather than `getBroadcast()`. Looks like it should work according to this: https://stackoverflow.com/a/13716784/4409409 – Daniel Nugent Dec 20 '17 at 05:19
0

Thanks everyone, finally i am able to make it work by following this post

I was using only notification, after disabling the notification sent from my php server and using data only did the trick, i can send notification and mainActivity does catch Putextra from the intent.

ian ajah
  • 91
  • 1
  • 6
0

If anyone still looking for getting custom data (Extras) firebase notification while app is swiped from recents or in background.

you can take look at my answer here

https://github.com/firebase/quickstart-android/issues/96#issuecomment-449936698

Abhishek Garg
  • 3,092
  • 26
  • 30