2016-07-23 176 views
1

假設我們有活動,它顯示有趣的圖片並將其命名爲FunnyActivity。點擊按鈕後,此活動可從MainActivity啓動,該活動是out應用程序中的基本Activity。我們還希望有時推送一些通知,當用戶點擊通知時,應該啓動FunnyActivity。所以我們加入這部分代碼:從通知中打開應用程序

Intent notificationIntent = new Intent(this, FunnyActivity.class); 
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

    PendingIntent intent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), notificationIntent, 0); 

這的PendingIntent在通知建設者

setContentIntent(intent) 

當然FunnyActivity是美麗的發射使用,但我們要打開MainActivity當用戶單擊後退按鈕上FunnyActivity 。

我們該如何做到這一點?請記住,當用戶回到MainActivity時,他可以再次從按鈕打開FunnyActivity。

+0

我不知道標準解決方案,這可能聽起來像一個黑客,但你可以做的其中一件事是在FunnyActivity中重寫'onBackPressed()',並在那裏啓動MainActivity。 – Shaishav

回答

4

試試這個:

// Intent for the activity to open when user selects the notification 
Intent detailsIntent = new Intent(this, DetailsActivity.class); 

// Use TaskStackBuilder to build the back stack and get the PendingIntent 
PendingIntent pendingIntent = 
     TaskStackBuilder.create(this) 
         // add all of DetailsActivity's parents to the stack, 
         // followed by DetailsActivity itself 
         .addNextIntentWithParentStack(upIntent) 
         .addNextIntent(detailsIntent); 
         .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 

NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
builder.setContentIntent(pendingIntent); 

來源:Create back stack when starting the activity

+0

看起來是正確的anwser!但是,在哪裏使用detailsIntent? – ThirdMartian

+0

@ThirdMartian之後.addNextIntentWithParentStack(upIntent) – shantanu

+0

@ThirdMartian我更新了答案,'upIntent'是你想要打開的意向MainActivity。 – shantanu

0

你可以試試這個:

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
Intent resultIntent = new Intent(this, FunnyActivity.class); 

        // Adds the back stack 
        stackBuilder.addParentStack(MainActivity.class); 
        // Adds the Intent to the top of the stack 
        stackBuilder.addNextIntent(resultIntent); 

Intent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)/*.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))*/ 
          .setSmallIcon(R.mipmap.ic_launcher) 
          .setContentTitle(title) 
          .setContentText(msg) 
          .setContentIntent(resultPendingIntent) 
          .setAutoCancel(true); 

這是如何可以實現問題的解決方案。希望這可以幫助你

相關問題