2016-07-23 106 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