zoukankan      html  css  js  c++  java
  • 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了。


  • 相关阅读:
    Match function in R
    Excel lastindex of a substring
    Print a file's last modified date in Bash
    IQR(Inter-Quartile Range)
    nohup 让进程在后台可靠运行的几种方法
    extension(类扩展)和 category(类别)
    Dart学习-操作符
    为什么我觉得Python烂的要死?
    自定义 Cordova插件(基础篇)
    Cordova入门系列(四)自定义Cordova插件--showToast
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/7015806.html
Copyright © 2011-2022 走看看