点击Android通知时设置全局变量

时间:2014-08-15 18:32:43

标签: android android-notifications

我需要设置

((MyApplication) this.getApplication()).globalVar(true);

当用户点击

private void sendNotification2(String msg) {

    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent mainIntent = new Intent(this, MainActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, mainIntent, 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_stat_gcm)
                    .setContentTitle("title")
                    /*.setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(msg))*/
                    .setAutoCancel(true)
                    .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID_2, mBuilder.build());
    //mNotificationManager.cancel(NOTIFICATION_ID);
    //mBuilder.flags |= mBuilder.FLAG_AUTO_CANCEL;
}

基本上就是全部。我需要在用户点击通知时设置该全局变量

2 个答案:

答案 0 :(得分:1)

您可以执行此解决方法:

1.在intent

中添加额外内容
mainIntent.putExtra("from_notification", true);

2.在您的活动中查看,如果已设置,请执行this.getApplication()).globalVar(true);

在您的活动onCreate

Intent intent = getIntent();
if(intent.hasExtra("from_notification") && intent.getBooleanExtra("from_notification")) {
    ((MyApplication) this.getApplication()).globalVar(true);
}

答案 1 :(得分:1)

尝试使用Singleton模式创建“全局变量”。维基百科有一篇关于thread-safe implementation的好文章。但是,这可能会超出您的需求。为什么需要设置全局布尔值?

编辑:

public class Singleton {
    // this private member variable is used in my example getter and setter below:
    private boolean mIsLoggedIn = false;

    private Singleton() {}
    private static class Holder { private static final Singleton INSTANCE = new Singleton(); }

    protected static Singleton getInstance() { return Holder.INSTANCE; }

    // Getters and Setters for your global variable(s)
    // Examples:
    protected boolean getIsLoggedIn() { return mIsLoggedIn = isLoggedIn; }
    protected void setIsLoggedIn(boolean isLoggedIn) { mIsLoggedIn = isLoggedIn; }
}