how to stay in the application after click on the notification

时间:2016-08-31 12:25:20

标签: android android-intent service notifications

in my android application i'm using a service to check every 10 seconds if there is a new message in the mysql database, and give me a notification, so when i click on the notification the messages activity start, but when i click on the back button i go out of the application instead of going back to HomeScreen

//show notification
public void ShowNotification(){
    NotificationCompat.Builder nbuild= new NotificationCompat.Builder(this)
            .setContentTitle("Message :"+username)
            .setContentText(messagetext)
            .setSubText(messageadddate)
            .setLargeIcon(bitmap)
            .setAutoCancel(true)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setSmallIcon(R.drawable.ic_stat_notification_red);
    Intent showMessages = new Intent(this, ShowMessages.class);
    TaskStackBuilder builder = TaskStackBuilder.create(this);
    builder.addParentStack(HomeScreen.class);
    builder.addNextIntent(showMessages);
    PendingIntent contentIntent = builder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    nbuild.setContentIntent(contentIntent);
    MessagesNotifManager.notify((int) System.currentTimeMillis(), nbuild.build());
}

2 个答案:

答案 0 :(得分:0)

这是正常的,默认情况下,后退按钮会导航后堆栈,而您的主页活动不在后台堆栈中。

以下是指南:https://developer.android.com/guide/components/tasks-and-back-stack.html

如果你想强制开放家庭活动,那么在活动中:

@Override
public void onBackPressed() {

    // start the intent(your home screen) you want, and finish() this. 
  super.onBackPressed(); // remove this.  
}

答案 1 :(得分:0)

我认为HomeScreen在这种情况下你正在谈论的是你的应用程序主屏幕(我们称之为MainActivity)。嗯..逻辑上只有你知道MainActivity控制所有其他活动.. Android不知道你的活动流程。

由于您只通知了通知栏中的通知活动...

 Intent showMessages = new Intent(this, ShowMessages.class);

android不会知道它必须回到MainActivity

但是,我会使用这种解决方法......可能不是最好的...但它会服务于目的......

@Override
public void onBackPressed() {
    Intent intentx;
    intentx = new Intent(thisContext, DashboardMainActivity.class);
    intentx.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    thisContext.startActivity(intentx);
    finish();
}