2016-07-23 105 views
0

我想在用戶拉下通知並點擊該通知時調用該活動...我該怎麼做?通知激活

這裏是我的代碼:

public class SetReminder extends AppCompatActivity { 
int notifyID = 1088; 

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

    TextView helpsubtitle = (TextView)findViewById(R.id.subtitle_help); 
    Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf"); 
    helpsubtitle.setTypeface(typeface); 

    NotificationCompat.Builder mBuilder = 

      new NotificationCompat.Builder(this) 
        .setSmallIcon(R.drawable.diamond) 
        .setContentTitle("Crystallise") 
        .setContentText("making your thoughts crystal clear"); 
    NotificationManager mNotificationManager = 
      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    mNotificationManager.notify(notifyID, mBuilder.build()); 
} 
} 

回答

1

首先,你需要創建一個Intent以指定您希望當用戶點擊該通知,即可啓動該活動。假設你想MainActivity打開單擊該通知時,可以使用下面的代碼創建的意圖:
Intent intent = new Intent(SetReminder.this, MainActivity.class);

然後,你必須指定一個PendingIntent,這是你給NotificationManager令牌,或任何其他外國申請一般:

PendingIntent pendingIntent = PendingIntent.getActivity(
     context, 0, 
     intent, PendingIntent.FLAG_CANCEL_CURRENT 
); 

使用.setContentIntent(pendingIntent)應用此pendingIntent到您的通知。

你的最終代碼應該是這樣的:

public class SetReminder extends AppCompatActivity { 
    int notifyID = 1088; 

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

     TextView helpsubtitle = (TextView)findViewById(R.id.subtitle_help); 
     Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf"); 
helpsubtitle.setTypeface(typeface); 

     Intent intent = new Intent(SetReminder.this, MainActivity.class); 
     PendingIntent pendingIntent = PendingIntent.getActivity(
       context, 0, 
       intent, PendingIntent.FLAG_CANCEL_CURRENT 
     ); 
     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.drawable.diamond) 
       .setContentIntent(pendingIntent) 
       .setContentTitle("Crystallise") 
       .setContentText("making your thoughts crystal clear"); 
     NotificationManager mNotificationManager = 
      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     mNotificationManager.notify(notifyID, mBuilder.build()); 
    } 
} 
+0

雷說無法解析符號背景+ asc42 –

+0

你需要傳遞的上下文。 由於您已經在一個活動中,並且您正在從活動本身創建通知,因此應該用'SetReminder.this'替換'context' – adhirajsinghchauhan