我已经尝试了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);
} }