android 常用功能代码快

来源:互联网 发布:nba15 16赛季数据 编辑:程序博客网 时间:2024/05/22 04:38

1.获取精确的屏幕尺寸:

   public static double getScreenPhysicalSize(Activity ctx) {        DisplayMetrics dm = new DisplayMetrics();        ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);        double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));        return diagonalPixels / (160 * dm.density);    }

2.判断是否为平板:

  public static boolean isTablet(Context context) {        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;    }

3.文字根据状态更改颜色android:TextColor 文件放在res/color目录下:

<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:color="#53c1bd" android:state_selected="true"/>    <item android:color="#53c1bd" android:state_focused="true"/>    <item android:color="#53c1bd" android:state_pressed="true"/>    <item android:color="#777777"/></selector>

4.背景色根据状态更改颜色android:backgroup(背景色不能直接给color 会报错):

复制代码<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_selected="true"><shape>            <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" />        </shape></item>    <item android:state_focused="true"><shape>            <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" />        </shape></item>    <item android:state_pressed="true"><shape>            <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" />        </shape></item>    <item><shape>            <gradient android:angle="0" android:centerColor="#00ff00" android:endColor="00ff00" android:startColor="00ff00" />        </shape></item></selector>

5.启动APK默认的Activity:

复制代码    public static void startApkActivity(final Context ctx, String packageName) {        PackageManager pm = ctx.getPackageManager();        PackageInfo pi;        try {            pi = pm.getPackageInfo(packageName, 0);            Intent intent = new Intent(Intent.ACTION_MAIN, null);            intent.addCategory(Intent.CATEGORY_LAUNCHER);            intent.setPackage(pi.packageName);            List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);            ResolveInfo ri = apps.iterator().next();            if (ri != null) {                String className = ri.activityInfo.name;                intent.setComponent(new ComponentName(packageName, className));                ctx.startActivity(intent);            }        } catch (NameNotFoundException e) {            Log.e("startActivity", e);        }    }复制代码

7.计算字宽(注意如果设置了textStyle,还要进一步的设置TextPaint):

   public static float GetTextWidth(String text, float Size) {        TextPaint FontPaint = new TextPaint();        FontPaint.setTextSize(Size);        return FontPaint.measureText(text);    }

8.获取应用程序下所有的Activity:

复制代码  public static ArrayList<String> getActivities(Context ctx) {      ArrayList<String> result = new ArrayList<String>();      Intent intent = new Intent(Intent.ACTION_MAIN, null);      intent.setPackage(ctx.getPackageName());      for (ResolveInfo info : ctx.getPackageManager().queryIntentActivities(intent, 0)) {          result.add(info.activityInfo.name);      }      return result;  }

9.检查字符串中是否包含汉字:

 public static boolean checkChinese(String sequence) {        final String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";        boolean result = false;        Pattern pattern = Pattern.compile(format);        Matcher matcher = pattern.matcher(sequence);        result = matcher.find();        return result;    }复制代码

10.检测字符串中只能包含:中文、数字、下划线、横线:

  public static boolean checkNickname(String sequence) {        final String format = "[^\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w-_]";        Pattern pattern = Pattern.compile(format);        Matcher matcher = pattern.matcher(sequence);        return !matcher.find();    } 

11.检查有没有应用程序来接收发出的intent:

  public static boolean isIntentAvailable(Context context, String action) {        final PackageManager packageManager = context.getPackageManager();        final Intent intent = new Intent(action);        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);        return list.size() > 0;    }

12.使用TransitionDrawbale实现渐变的效果(比使用AlphaAnimation效果要好,可以避免出现闪烁问题):

  private void setImageBitmap(ImageView imageView, Bitmap bitmap) {        // Use TransitionDrawable to fade in.        final TransitionDrawable td = new TransitionDrawable(new Drawable[] { new ColorDrawable(android.R.color.transparent), new BitmapDrawable(mContext.getResources(), bitmap) });        //noinspection deprecation            imageView.setBackgroundDrawable(imageView.getDrawable());        imageView.setImageDrawable(td);        td.startTransition(200);    }复制代码

13.扫描指定的文件(用途:从本软件新增、修改、删除图片、文件某一个文件(音频、视频)需要更新系统媒体库时使用,不必扫描整个SD卡):

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

14.Dip转px

    public static int dipToPX(final Context ctx, float dip) {        return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, ctx.getResources().getDisplayMetrics());    }

15.获取已安装apk的路径:

    PackageManager pm = getPackageManager();    for (ApplicationInfo app : pm.getInstalledApplications(0)) {         Log.d("PackageList", "package: " + app.packageName + ", sourceDir: " + app.sourceDir);    }        输出如下:    package: com.tmobile.thememanager, sourceDir: /system/app/ThemeManager.apk    package: com.touchtype.swiftkey, sourceDir: /data/app/com.touchtype.swiftkey-1.apk

16.多进程Preferences数据共享

   public static void putStringProcess(Context ctx, String key, String value) {        SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS);        Editor editor = sharedPreferences.edit();        editor.putString(key, value);        editor.commit();    }    public static String getStringProcess(Context ctx, String key, String defValue) {        SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS);        return sharedPreferences.getString(key, defValue);    }

17.泛型arrayList转数组:

 @SuppressWarnings("unchecked")    public static <T> T[] toArray(Class<?> cls, ArrayList<T> items) {        if (items == null || items.size() == 0) {            return (T[]) Array.newInstance(cls, 0);        }        return items.toArray((T[]) Array.newInstance(cls, items.size()));    }

18.保存恢复ListView当前位置(可以保存在Preference中或者是数据库中,数据加载完成后再设置):

 private void saveCurrentPosition() {        if (mListView != null) {            int position = mListView.getFirstVisiblePosition();            View v = mListView.getChildAt(0);            int top = (v == null) ? 0 : v.getTop();            //保存position和top        }    }    private void restorePosition() {        if (mFolder != null && mListView != null) {            int position = 0;//取出保存的数据            int top = 0;//取出保存的数据            mListView.setSelectionFromTop(position, top);        }    }复制代码

19.调用便携式热点和数据共享设置

复制代码    public static Intent getHotspotSetting() {        Intent intent = new Intent();        intent.setAction(Intent.ACTION_MAIN);        ComponentName com = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");        intent.setComponent(com);        return intent;    }

20.格式化输出的IP地址

    public static String getIp(Context ctx) {        return Formatter.formatIpAddress((WifiManager) ctx.getSystemService(Context.WIFI_SERVICE).getConnectionInfo().getIpAddress());    }

21.文件夹排序(先文件夹排序,后文件排序):

  public static void sortFiles(File[] files) {        Arrays.sort(files, new Comparator<File>() {            @Override            public int compare(File lhs, File rhs) {                //返回负数表示o1 小于o2,返回0 表示o1和o2相等,返回正数表示o1大于o2。                 boolean l1 = lhs.isDirectory();                boolean l2 = rhs.isDirectory();                if (l1 && !l2)                    return -1;                else if (!l1 && l2)                    return 1;                else {                    return lhs.getName().compareTo(rhs.getName());                }            }        });    }复制代码

22.发送不重复的通知(Notification):
代码说明:

        关键点在这个requestCode,这里使用的是当前系统时间,巧妙的保证了每次都是一个新的Notification产生。
复制代码    public static void sendNotification(Context context, String title,            String message, Bundle extras) {        Intent mIntent = new Intent(context, FragmentTabsActivity.class);        mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        mIntent.putExtras(extras);        int requestCode = (int) System.currentTimeMillis();        PendingIntent mContentIntent = PendingIntent.getActivity(context,                requestCode, mIntent, 0);        Notification mNotification = new NotificationCompat.Builder(context)                .setContentTitle(title).setSmallIcon(R.drawable.app_icon)                .setContentIntent(mContentIntent).setContentText(message)                .build();        mNotification.flags |= Notification.FLAG_AUTO_CANCEL;        mNotification.defaults = Notification.DEFAULT_ALL;        NotificationManager mNotificationManager = (NotificationManager) context                .getSystemService(Context.NOTIFICATION_SERVICE);        mNotificationManager.notify(requestCode, mNotification);    }

23.代码设置TextView的样式
使用过自定义Dialog可能马上会想到用如下代码:

        new TextView(this,null,R.style.text_style);         但你运行这代码你会发现毫无作用!正确用法:    new TextView(new ContextThemeWrapper(this, R.style.text_style))
  1. ip地址转成8位十六进制串:
 /** ip转16进制 */    public static String ipToHex(String ips) {        StringBuffer result = new StringBuffer();        if (ips != null) {            StringTokenizer st = new StringTokenizer(ips, ".");            while (st.hasMoreTokens()) {                String token = Integer.toHexString(Integer.parseInt(st.nextToken()));                if (token.length() == 1)                    token = "0" + token;                result.append(token);            }        }        return result.toString();    }    /** 16进制转ip */    public static String texToIp(String ips) {        try {            StringBuffer result = new StringBuffer();            if (ips != null && ips.length() == 8) {                for (int i = 0; i < 8; i += 2) {                    if (i != 0)                        result.append('.');                    result.append(Integer.parseInt(ips.substring(i, i + 2), 16));                }            }            return result.toString();        } catch (NumberFormatException ex) {            Logger.e(ex);        }        return "";    }

25.WebView保留缩放功能但隐藏缩放控件:

  mWebView.getSettings().setSupportZoom(true);        mWebView.getSettings().setBuiltInZoomControls(true);        if (DeviceUtils.hasHoneycomb())              mWebView.getSettings().setDisplayZoomControls(false);

注意:setDisplayZoomControls是在API Level 11中新增。
26.获取网络类型名称:

 public static String getNetworkTypeName(Context context) {        if (context != null) {            ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);            if (connectMgr != null) {                NetworkInfo info = connectMgr.getActiveNetworkInfo();                if (info != null) {                    switch (info.getType()) {                    case ConnectivityManager.TYPE_WIFI:                        return "WIFI";                    case ConnectivityManager.TYPE_MOBILE:                        return getNetworkTypeName(info.getSubtype());                    }                }            }        }        return getNetworkTypeName(TelephonyManager.NETWORK_TYPE_UNKNOWN);    }    public static String getNetworkTypeName(int type) {        switch (type) {        case TelephonyManager.NETWORK_TYPE_GPRS:            return "GPRS";        case TelephonyManager.NETWORK_TYPE_EDGE:            return "EDGE";        case TelephonyManager.NETWORK_TYPE_UMTS:            return "UMTS";        case TelephonyManager.NETWORK_TYPE_HSDPA:            return "HSDPA";        case TelephonyManager.NETWORK_TYPE_HSUPA:            return "HSUPA";        case TelephonyManager.NETWORK_TYPE_HSPA:            return "HSPA";        case TelephonyManager.NETWORK_TYPE_CDMA:            return "CDMA";        case TelephonyManager.NETWORK_TYPE_EVDO_0:            return "CDMA - EvDo rev. 0";        case TelephonyManager.NETWORK_TYPE_EVDO_A:            return "CDMA - EvDo rev. A";        case TelephonyManager.NETWORK_TYPE_EVDO_B:            return "CDMA - EvDo rev. B";        case TelephonyManager.NETWORK_TYPE_1xRTT:            return "CDMA - 1xRTT";        case TelephonyManager.NETWORK_TYPE_LTE:            return "LTE";        case TelephonyManager.NETWORK_TYPE_EHRPD:            return "CDMA - eHRPD";        case TelephonyManager.NETWORK_TYPE_IDEN:            return "iDEN";        case TelephonyManager.NETWORK_TYPE_HSPAP:            return "HSPA+";        default:            return "UNKNOWN";        }    }复制代码

27.Android解压Zip包:

复制代码    /**     * 解压一个压缩文档 到指定位置     *      * @param zipFileString 压缩包的名字     * @param outPathString 指定的路径     * @throws Exception     */    public static void UnZipFolder(String zipFileString, String outPathString) throws Exception {        java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(zipFileString));        java.util.zip.ZipEntry zipEntry;        String szName = "";        while ((zipEntry = inZip.getNextEntry()) != null) {            szName = zipEntry.getName();            if (zipEntry.isDirectory()) {                // get the folder name of the widget                szName = szName.substring(0, szName.length() - 1);                java.io.File folder = new java.io.File(outPathString + java.io.File.separator + szName);                folder.mkdirs();            } else {                java.io.File file = new java.io.File(outPathString + java.io.File.separator + szName);                file.createNewFile();                // get the output stream of the file                java.io.FileOutputStream out = new java.io.FileOutputStream(file);                int len;                byte[] buffer = new byte[1024];                // read (len) bytes into buffer                while ((len = inZip.read(buffer)) != -1) {                    // write (len) byte from buffer at the position 0                    out.write(buffer, 0, len);                    out.flush();                }                out.close();            }        }//end of while        inZip.close();    }//end of func复制代码
  1. 从assets中读取文本和图片资源:
复制代码    /** 从assets 文件夹中读取文本数据 */    public static String getTextFromAssets(final Context context, String fileName) {        String result = "";        try {            InputStream in = context.getResources().getAssets().open(fileName);            // 获取文件的字节数            int lenght = in.available();            // 创建byte数组            byte[] buffer = new byte[lenght];            // 将文件中的数据读到byte数组中            in.read(buffer);            result = EncodingUtils.getString(buffer, "UTF-8");            in.close();        } catch (Exception e) {            e.printStackTrace();        }        return result;    }    /** 从assets 文件夹中读取图片 */    public static Drawable loadImageFromAsserts(final Context ctx, String fileName) {        try {            InputStream is = ctx.getResources().getAssets().open(fileName);            return Drawable.createFromStream(is, null);        } catch (IOException e) {            if (e != null) {                e.printStackTrace();            }        } catch (OutOfMemoryError e) {            if (e != null) {                e.printStackTrace();            }        } catch (Exception e) {            if (e != null) {                e.printStackTrace();            }        }        return null;    }

29.展开、收起状态栏 :

复制代码    public static final void collapseStatusBar(Context ctx) {        Object sbservice = ctx.getSystemService("statusbar");        try {            Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");            Method collapse;            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {                collapse = statusBarManager.getMethod("collapsePanels");            } else {                collapse = statusBarManager.getMethod("collapse");            }            collapse.invoke(sbservice);        } catch (Exception e) {            e.printStackTrace();        }    }    public static final void expandStatusBar(Context ctx) {        Object sbservice = ctx.getSystemService("statusbar");        try {            Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");            Method expand;            if (Build.VERSION.SDK_INT >= 17) {                expand = statusBarManager.getMethod("expandNotificationsPanel");            } else {                expand = statusBarManager.getMethod("expand");            }            expand.invoke(sbservice);        } catch (Exception e) {            e.printStackTrace();        }    }复制代码

用途:可用于点击Notifacation之后收起状态栏
30. 获取状态栏高度:

复制代码    public static int getStatusBarHeight(Context context){        Class<?> c = null;        Object obj = null;        Field field = null;        int x = 0, statusBarHeight = 0;        try {            c = Class.forName("com.android.internal.R$dimen");            obj = c.newInstance();            field = c.getField("status_bar_height");            x = Integer.parseInt(field.get(obj).toString());            statusBarHeight = context.getResources().getDimensionPixelSize(x);        } catch (Exception e1) {            e1.printStackTrace();        }        return statusBarHeight;    }复制代码

31.ListView使用ViewHolder极简写法

复制代码    public static <T extends View> T getAdapterView(View convertView, int id) {        SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag();        if (viewHolder == null) {            viewHolder = new SparseArray<View>();            convertView.setTag(viewHolder);        }        View childView = viewHolder.get(id);        if (childView == null) {            childView = convertView.findViewById(id);            viewHolder.put(id, childView);        }        return (T) childView;    }

用法:

 @Override    public View getView(int position, View convertView, ViewGroup parent) {        if (convertView == null) {            convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feed_item, parent, false);        }        ImageView thumnailView = getAdapterView(convertView, R.id.video_thumbnail);        ImageView avatarView =  getAdapterView(convertView, R.id.user_avatar);        ImageView appIconView = getAdapterView(convertView, R.id.app_icon);

用起来非常简练,将ViewHolder隐于无形。
32. 设置Activity透明

复制代码    <style name="TransparentActivity" parent="AppBaseTheme">        <item name="android:windowBackground">@android:color/transparent</item>        <item name="android:colorBackgroundCacheHint">@null</item>        <item name="android:windowIsTranslucent">true</item>        <item name="android:windowNoTitle">true</item>        <item name="android:windowContentOverlay">@null</item>    </style>
    说明:AppBaseTheme一般是你application指定的android:theme是啥这里就是啥,否则Activity内部的空间风格可能不一致。    用途:用于模拟Dialog效果,比如再Service中没法用Dialog,就可以用Activity来模拟

33.代码切换全屏

复制代码    //切换到全屏    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);    getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);    //切换到非全屏    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
    注意:切换到全屏时,底部的虚拟按键仍然是显示的。次方法可多次调用用于切换    用途:播放器界面经常会用到 

34.调用开发者选项中显示触摸位置功能

android.provider.Settings.System.putInt(getContentResolver(), "show_touches", 1);

设置1显示,设置0不显示。
35.获取设备上已安装并且可启动的应用列表

 Intent intent = new Intent(Intent.ACTION_MAIN);            intent.addCategory(Intent.CATEGORY_LAUNCHER);            List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0)

注意:使用getInstalledApplications会返回很多无法启动甚至没有图标的系统应用。ResolveInfo.activityInfo.applicationInfo也能取到你想要的数据。

WebView相关

36.打开网页时不调用系统浏览器, 而是在本WebView中显示:

复制代码mWebView.setWebViewClient(new WebViewClient(){      @Override      public boolean shouldOverrideUrlLoading(WebView view, String url) {          view.loadUrl(url);          return true;      }  });复制代码

37.通过java代码调用javascript

WebSettings webSettings =   mWebView .getSettings();       webSettings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new Object() {                   public void clickOnAndroid() {                       mHandler.post(new Runnable() {                           public void run() {                               webview.loadUrl("javascript:wave()");                           }                       });                   }               }, "demo"); 复制代码
  1. 按返回键时, 不退出程序而是返回上一浏览页面:
public boolean onKeyDown(int keyCode, KeyEvent event) {               if ((keyCode == KeyEvent.KEYCODE_BACK) &&   mWebView .canGoBack()) {                   webview.goBack();                          return true;               }               return super.onKeyDown(keyCode, event);           }复制代码

39.android下载速度计算:

long startTime = System.currentTimeMillis(); // 开始下载时获取开始时间long curTime = System.currentTimeMillis();int usedTime = (int) ((curTime-startTime)/1000);if(usedTime==0)usedTime = 1;int downloadSpeed = (downloadSize/usedTime)/1024; // 下载速度

40.android中不混淆类中函数:

情况一:混淆不同的函数aTest、bTest-keep class com.zony.Test {    void aTest(byte[], int, int);    void bTest(String, int, int);}情况二:混淆相同的函数aTest(aTest参数不同)复制代码错误混淆方式:-keep class com.zony.Test {    void aTest(byte[], int, int);    void aTest(String, int, int);}此种混淆,函数aTest(String, int, int);会被混淆(咎其原因未深究)正确混淆方式:-keep class com.zony.Test {    void aTest*(...);}

41.Android中再按一次退出程序的实现:

private long exitTime = 0;@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){if((System.currentTimeMillis()-exitTime) > 2000){Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();exitTime = System.currentTimeMillis();} else {finish();System.exit(0);}return true;}return super.onKeyDown(keyCode, event);} 

42.Android 弹出对话框来退出程序:

主页面中覆盖onKeyDown方法    @Override    public boolean onKeyDown(int keyCode, KeyEvent event) {        // TODO Auto-generated method stub        if(keyCode == KeyEvent.KEYCODE_BACK){            ShowDialog.showExitDialog(MainActivity.this);        }        return true;    }ShowDialog.javapublic class ShowDialog{    public static void showExitDialog(Activity context){        //实例化一个关于退出的警示对话框        final AlertDialog exitDialog = new AlertDialog.Builder(context).create();        exitDialog.setTitle("提示");        exitDialog.setMessage("是否退出程序");        //点击“是”的时候触发的事件        exitDialog.setButton("是", new AlertDialog.OnClickListener(){            public void onClick(DialogInterface dialog, int which) {                // TODO Auto-generated method stub                exitDialog.dismiss();                System.out.println("the wopai program exit");                System.exit(0);            }        });        //点击“否”的时候触发的事件        exitDialog.setButton2("否", new AlertDialog.OnClickListener(){            public void onClick(DialogInterface dialog, int which) {                // TODO Auto-generated method stub                exitDialog.dismiss();            }        });        //显示对话框        exitDialog.show();    }}
  1. Android Webview实现图片、文件上传及启动相机功能 :
    1.声明的数据:
    private String mCameraFilePath = null;      private ValueCallback<Uri> mUploadMessage;// 表单的数据信息      private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调</span>  
    2.
    <span style="font-size:18px;">private WebChromeClient webChromeClient = new WebChromeClient() {              // For Android 3.0+              public void openFileChooser(ValueCallback<Uri> uploadMsg) {                  if (uploadMsg == null) {                      return;                  }                  mUploadMessage = uploadMsg;                  Intent i = new Intent(Intent.ACTION_GET_CONTENT);                  i.addCategory(Intent.CATEGORY_OPENABLE);                  i.setType("image/*");                  activity.startActivityForResult(                          Intent.createChooser(i, "File Chooser"),                          FILECHOOSER_RESULTCODE);              }              // For Android 3.0+              public void openFileChooser(ValueCallback uploadMsg, String acceptType) {                  if (uploadMsg == null) {                      return;                  }                  mUploadMessage = uploadMsg;                  Intent i = new Intent(Intent.ACTION_GET_CONTENT);                  i.addCategory(Intent.CATEGORY_OPENABLE);                  i.setType("*/*");                  activity.startActivityForResult(                          Intent.createChooser(i, "File Browser"),                          FILECHOOSER_RESULTCODE);              }              // For Android 4.1              public void openFileChooser(ValueCallback<Uri> uploadMsg,                      String acceptType, String capture) {                  if (uploadMsg == null) {                      return;                  }                  mUploadMessage = uploadMsg;                  Intent i = new Intent(Intent.ACTION_GET_CONTENT);                  i.addCategory(Intent.CATEGORY_OPENABLE);                  i.setType("image/*");                  activity.startActivityForResult(                          Intent.createChooser(i, "File Chooser"),                          FILECHOOSER_RESULTCODE);              }              private Intent createDefaultOpenableIntent() {                  // Create and return a chooser with the default OPENABLE                  // actions including the camera, camcorder and sound                  // recorder where available.                  Intent i = new Intent(Intent.ACTION_GET_CONTENT);                  i.addCategory(Intent.CATEGORY_OPENABLE);                  i.setType("*/*");                  Intent chooser = createChooserIntent(createCameraIntent(),                          createCamcorderIntent(), createSoundRecorderIntent());                  chooser.putExtra(Intent.EXTRA_INTENT, i);                  return chooser;              }              private Intent createChooserIntent(Intent... intents) {                  Intent chooser = new Intent(Intent.ACTION_CHOOSER);                  chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);                  chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");                  return chooser;              }              private Intent createCameraIntent() {                  Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                  File externalDataDir = Environment                          .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);                  System.out.println("externalDataDir:" + externalDataDir);                  File cameraDataDir = new File(externalDataDir.getAbsolutePath()                          + File.separator + "browser-photo");                  cameraDataDir.mkdirs();                  mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator                          + System.currentTimeMillis() + ".jpg";                  System.out.println("mcamerafilepath:" + mCameraFilePath);                  cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,                          Uri.fromFile(new File(mCameraFilePath)));                  return cameraIntent;              }              private Intent createCamcorderIntent() {                  return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);              }              private Intent createSoundRecorderIntent() {                  return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);              }      };  
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {              if (requestCode == FILECHOOSER_RESULTCODE) {                  if (null == mUploadMessage)                      return;                  Uri result = intent == null || resultCode != Activity.RESULT_OK ? null                          : intent.getData();                  if (result == null && intent == null                          && resultCode == Activity.RESULT_OK) {                      File cameraFile = new File(mCameraFilePath);                      if (cameraFile.exists()) {                          result = Uri.fromFile(cameraFile);                          activity.sendBroadcast(new Intent(                                  Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));                      }                  }                  mUploadMessage.onReceiveValue(result);                  mUploadMessage = null;              }       }  
0 0