Android調用第三方App,android第三方app

來源:互聯網
上載者:User

Android調用第三方App,android第三方app

  1. private List<Map<String, Object>> list = null;  
  2. private PackageManager mPackageManager;  
  3. private List<ResolveInfo> mAllApps;  
  4. private Context mContext;  
  5.   
  6. /** 
  7.  * 檢查系統應用程式,並開啟 
  8.  */  
  9. private void openApp(){  
  10.     //應用過濾條件  
  11.     Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);  
  12.     mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
  13.     mPackageManager = mContext.getPackageManager();  
  14.     mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);  
  15.     //按報名排序  
  16.     Collections.sort(mAllApps, new ResolveInfo.DisplayNameComparator(mPackageManager));  
  17.   
  18.     for(ResolveInfo res : mAllApps){  
  19.         //該應用的包名和主Activity  
  20.         String pkg = res.activityInfo.packageName;  
  21.         String cls = res.activityInfo.name;  
  22.   
  23.         // 開啟QQ  
  24.         if(pkg.contains("qq")){  
  25.             ComponentName componet = new ComponentName(pkg, cls);  
  26.             Intent intent = new Intent();  
  27.             intent.setComponent(componet);  
  28.             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  29.             mContext.startActivity(intent);  
  30.         }  
  31.     }  
  32. }  

  33. 很多人使用startActivity時候,會碰到如下的異常:

    Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?


        我曾經也遇到過,不過後來研究了一下之後,明白了原理,記下來,以為碰到同樣困擾的兄弟們解惑。


        都知道,Context中有一個startActivity方法,Activity繼承自Context,重載了startActivity方法。如果使用Activity的startActivity方法,不會有任何限制,而如果使用Context的startActivity方法的話,就需要開啟一個新的task,遇到上面那個異常的,都是因為使用了Context的startActivity方法。解決辦法是,加一個flag。

    [java] view plaincopy
    1. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    

    這樣就可以再新的task裡面啟動這個Activity了。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.