通知激活

时间:2016-07-23 13:40:01

标签: android notifications

我想在用户下拉通知并点击该通知时调用该活动...我该怎么做?

这是我的代码:

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 个答案:

答案 0 :(得分:1)

首先,您需要创建一个Intent,指定用户点击通知时要启动的活动。假设您希望在单击通知时打开MainActivity,请使用以下代码创建意图:
Intent intent = new Intent(SetReminder.this, MainActivity.class);

然后,您必须指定一个PendingIntent,这是您提供给NotificationManager或任何其他外国应用程序的令牌:

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

使用pendingIntent将此.setContentIntent(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());
    }
}