2013-10-17 52 views
5

如何在通知按鈕點擊後關閉狀態欄?單擊按鈕通知時關閉狀態欄

我試過this,但我有一個例外:

java.lang.NoSuchMethodException: collapse [] 
    at java.lang.Class.getConstructorOrMethod(Class.java:460) 
    at java.lang.Class.getMethod(Class.java:915) 
    ... 

我的代碼:

NotificationCompat.Builder builder = new NotificationCompat.Builder(context) 
    .setSmallIcon(R.drawable.icon) 
    .setContentTitle("Sync Failed") 
    .setContentText("Lorem ipsum dolor sit amet") 
    .setStyle(new NotificationCompat.BigTextStyle().bigText("Lorem ipsum dolor sit amet")) 
    .addAction(R.drawable.change, "Change Pass", pChangePass) 
    .addAction(R.drawable.remove, "Ignore", pIgnore) 
    .setAutoCancel(false); 
mNotificationManager.notify(accountUnique, builder.build()); 

在NotificationIntent類

@Override 
public void onReceive(Context context, Intent intent) { 
    int notificationID = intent.getExtras().getInt("NOT_ID"); 
    this.callbackContext = StatusBarNotification.getCallback(); 
    this.mNotificationManager = StatusBarNotification.getNotificationManager(); 

    this.mNotificationManager.cancel(notificationID); 
    this.callbackContext.success(returnJSON(intent)); 
} 

回答

0

好吧,我解決了這個問題。

private int currentApiVersion = android.os.Build.VERSION.SDK_INT; 
... 

Object sbservice = context.getSystemService("statusbar"); 
try { 
    Class<?> statusbarManager = Class.forName("android.app.StatusBarManager"); 
    if (currentApiVersion <= 16) { 
     Method collapse = statusbarManager.getMethod("collapse"); 
     collapse.invoke(sbservice); 
    } else { 
     Method collapse2 = statusbarManager.getMethod("collapsePanels"); 
     collapse2.invoke(sbservice); 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+4

你真的應該接受薩姆·魯的評論 - 您的解決方案可能會停止在任何未來版本的工作,因爲使用了非公共API。正如你所看到的,你必須添加'如果api <= 16' - 可能很快你就需要添加'if api <= 19' – imbryk

+0

同意上面的評論。 Sam的答案簡單得多,並且不涉及版本號。 – Saik

30

以下解決方案應該更簡單,沒有使用非公開的API:

Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 
context.sendBroadcast(it); 
+1

你可以告訴在哪裏使用這個onRecieve或動作意圖? – Ajeet

+0

工作就像魅力!謝謝。只需在onRecieve中放置2個代碼行即可。 –

+0

是的,這工作。謝謝。 – Saik