文章出處

類似桌面圖標打開App的Intent

程序中需要一種通知,點擊后的效果需要像點擊桌面圖標那樣:

  • 程序在前臺就什么也不干。
  • 程序在后臺,就切換到前臺。
  • 程序未啟動,就啟動程序。

點擊通知后,通知本身跳轉到Receiver,然后onReceive方法里面處理通知的跳轉intent,startActivity使用onReceive的context或者Application都行。
創建打開app的intent,自己嘗試了一些寫法有點bug——多次打開app——偶然性,而且不穩定?
最終從 launcher的源碼中找到了系統桌面圖標的點擊打開app使用的Intent:

ComponentName className = new ComponentName(packageName, activityName);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(className);
int launchFlags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED;
intent.setFlags(launchFlags);

注意:
上面最關鍵的是launchFlags,可以避免多次啟動程序:也就是程序已經啟動了,在后臺,然后點擊通知后又閃出啟動頁面。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 AutoPoster 的頭像
    AutoPoster

    互聯網 - 大數據

    AutoPoster 發表在 痞客邦 留言(0) 人氣()