3

我在android中的通知有问题,每当我每次点击通知时,我都必须再次调用相同的活动,但据我认为新活动被调用但前一个也在后端运行,由于我的代码一次又一次地运行(因为多个实例)

请帮助我每次单击通知时如何解决或关闭多个实例。

代码

public void notificationforChat(CharSequence message,String toJid, int notificationID) {

    int notificationCount = 1;
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    int icon = R.drawable.ic_launcher;
    CharSequence tickerText = message;
    long when = System.currentTimeMillis();
    Notification notification = new Notification(icon, tickerText, when);
    //notification.number = notificationCount++;
    Context context = getApplicationContext();



    CharSequence contentTitle = "Chat";
    CharSequence contentText = message;
    Intent notificationIntentforChat = new Intent(this, UserChatActivity.class);
    notificationIntentforChat.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

    notificationIntentforChat.putExtra("userNameVal", toJid);       
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            notificationIntentforChat, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, contentTitle, contentText,
            contentIntent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults = Notification.DEFAULT_ALL;   
    mNotificationManager.notify(notificationID, notification);
}

谢谢

4

4 回答 4

1

防止多个活动实例。

你可以android:launchMode="singleTask"在你的活动中使用

<activity
            android:launchMode="singleTask"
            android:name=".UserChatActivity"
            android:label="Your title" > 

....
</activity>

一旦你调用它。onNewIntent(Intent)将以新的意图触发

    @Override
    protected void onNewIntent(Intent intent) {

       super.onNewIntent(intent);      


    }
于 2012-11-16T06:02:16.847 回答
1

android:launchMode="singleInstance"以模式或 模式启动活动怎么样android:launchMode="singleTop"。我认为这有帮助。

于 2012-11-16T06:07:21.940 回答
1

将该活动的以下代码放在 maifest 中:

android:launchMode="singleTop"

然后为了在再次调用活动时处理新的更改,请覆盖以下方法。

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);      
    //Do your new intent handling here.     
}

您放入清单中的代码确保只创建该活动的一个实例。您可以在该活动的 onNewIntent 覆盖方法中处理新意图所需的更改。

于 2012-11-16T05:59:20.423 回答
0

添加到您的呼叫意图

mIntent. setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

添加到清单中的活动

android:launchMode="singleTop"
于 2016-03-03T12:13:27.577 回答