android开发的常用小功能汇总(持续更新)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mattdong0106/article/details/44020619

1.判断应用是否在运行

 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(MY_PKG_NAME) && info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
                isAppRunning = true;
                break;
            } else {
                isAppRunning = false;
            }
        }

需要权限:

<uses-permission android:name="android.permission.GET_TASKS" />

2.启动一个APP

Intent intent = new Intent(Intent.ACTION_MAIN);  
intent.addCategory(Intent.CATEGORY_LAUNCHER);              
ComponentName cn = new ComponentName(packageName, className);              
intent.setComponent(cn);  
startActivity(intent);  

3.Monkey测试

详细的monkey介绍,和options的参数请查看 (http://developer.android.com/guide/developing/tools/monkey.html

命令行示例,它启动指定的应用程序,并向其发送500个伪随机事件:

adb shell monkey -p your.package.name -vvv 500 > monkeytest.txt 
-p表示对象包  -v 为 verbose的缩写(信息级别就是日志的详细程度),就是详细输出事件等级,这个3个v就是输出等级1至3的所有事件.(使用管道命令将输出结果放到一个文本里面方便查看)


4.强制横竖屏

在配置文件中对Activity节点添加android:screenOrientation属性(landscape是横向,portrait是纵向)

android:screenOrientation="portrait">

5.全屏

4.0以前,在Activity的onCreate方法中的setContentView(myview)调用之前添加下面代码

requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏


4.0以上版本隐藏NavigationBar

 private void hideNavigation() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }


6.获取当前手机号

        /* 
         * 获取当前的手机号 
         */ 
        public String getLocalNumber() { 
                TelephonyManager tManager = (TelephonyManager) this 
                                .getSystemService(TELEPHONY_SERVICE); 
                String number = tManager.getLine1Number(); 
                return number; 
        } 

7.检查是否有网络连接


public boolean checkInternet() { 
        ConnectivityManager cm = (ConnectivityManager) this 
                .getSystemService(Context.CONNECTIVITY_SERVICE); 
        NetworkInfo info = cm.getActiveNetworkInfo(); 
        if (info != null && info.isConnected()) { 
            // 能连接Internet 
            return true; 
        } else { 
            // 不能连接到 
            return false; 
        } 
    } 

8.计算已使用内存的百分比

   /** 
     * 计算已使用内存的百分比,并返回。 
     *  
     * @param context 
     *            可传入应用程序上下文。 
     * @return 已使用内存的百分比,以字符串形式返回。 
     */  
    public static String getUsedPercentValue(Context context) {  
        String dir = "/proc/meminfo";  
        try {  
            FileReader fr = new FileReader(dir);  
            BufferedReader br = new BufferedReader(fr, 2048);  
            String memoryLine = br.readLine();  
            String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));  
            br.close();  
            long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));  
            long availableSize = getAvailableMemory(context) / 1024;  
            int percent = (int) ((totalMemorySize - availableSize) / (float) totalMemorySize * 100);  
            return percent + "%";  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return "null";  
    }  
  
    /** 
     * 获取当前可用内存,返回数据以字节为单位。 
     *  
     * @param context 
     *            可传入应用程序上下文。 
     * @return 当前可用内存。 
     */  
    private static long getAvailableMemory(Context context) {  
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();  
        getActivityManager(context).getMemoryInfo(mi);  
        return mi.availMem;  
    } 


9.系统设置大号字体后避免布局错乱

@Override
protected void onResume() {
    super.onResume();
    Resources resource = getResources();
    Configuration c =resource.getConfiguration();
    c.fontScale = 1.0f;
    resource.updateConfiguration(c, resource.getDisplayMetrics());
}


10.不让app显示在最近任务列表中:

PS:虽然不显示,但是依然可以被杀死#-_-#
android:excludeFromRecents=“true”


11.dp转px

public static int dp2px(Context context, int dp) {
    final float fDensity = context.getResources().getDisplayMetrics().density;
    return (int) (dp * fDensity + 0.5f);
}

12.防止快速点击

private long mLastClickTime; 

public boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - mLastClickTime;
        if (0 < timeD && timeD < 1000) {
            return true;
        }
        mLastClickTime = time;
        return false;
    }


13.获取屏幕宽高和像素密度等

Point point = new Point();
getWindowManager().getDefaultDisplay().getSize(point);
Log.d(TAG, "the screen size is " + point.toString());
getWindowManager().getDefaultDisplay().getRealSize(point);
Log.d(TAG,"the screen real size is "+point.toString());
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
Log.d(TAG,"Density is "+displayMetrics.density + " densityDpi is "+displayMetrics.densityDpi+" height: "+displayMetrics.heightPixels+
        " width: "+displayMetrics.widthPixels);

14.获取当前进程的名称

public static String getProcessName(Context cxt, int pid) {  
    ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);  
    List<RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();  
    if (runningApps == null) {  
        return null;  
    }  
    for (RunningAppProcessInfo procInfo : runningApps) {  
        if (procInfo.pid == pid) {  
            return procInfo.processName;  
        }  
    }  
    return null;  
} 


15.过滤HTML标签,把HTML内容转为文本格式 

/** 
     * 把html内容转为文本 
     * @param html 需要处理的html文本 
     * @param filterTags 需要保留的html标签样式 
     * @return 
     */  
    public static String trimHtml2Txt(String html, String[] filterTags){      
        html = html.replaceAll("\\<head>[\\s\\S]*?</head>(?i)", "");//去掉head  
        html = html.replaceAll("\\<!--[\\s\\S]*?-->", "");//去掉注释  
        html = html.replaceAll("\\<![\\s\\S]*?>", "");  
        html = html.replaceAll("\\<style[^>]*>[\\s\\S]*?</style>(?i)", "");//去掉样式  
        html = html.replaceAll("\\<script[^>]*>[\\s\\S]*?</script>(?i)", "");//去掉js  
        html = html.replaceAll("\\<w:[^>]+>[\\s\\S]*?</w:[^>]+>(?i)", "");//去掉word标签  
        html = html.replaceAll("\\<xml>[\\s\\S]*?</xml>(?i)", "");  
        html = html.replaceAll("\\<html[^>]*>|<body[^>]*>|</html>|</body>(?i)", "");  
        html = html.replaceAll("\\\r\n|\n|\r", " ");//去掉换行  
        html = html.replaceAll("\\<br[^>]*>(?i)", "\n");  
        List<String> tags = new ArrayList<String>();  
        List<String> s_tags = new ArrayList<String>();  
        List<String> halfTag = Arrays.asList(new String[]{"img","table","thead","th","tr","td"});//  
        if(filterTags != null && filterTags.length > 0){  
            for (String tag : filterTags) {  
                tags.add("<"+tag+(halfTag.contains(tag)?"":">"));//开始标签  
                if(!"img".equals(tag)) tags.add("</"+tag+">");//结束标签  
                s_tags.add("#REPLACETAG"+tag+(halfTag.contains(tag)?"":"REPLACETAG#"));//尽量替换为复杂一点的标记,以免与显示文本混合,如:文本中包含#td、#table等  
                if(!"img".equals(tag)) s_tags.add("#REPLACETAG/"+tag+"REPLACETAG#");  
            }  
        }  
        html = ExStringUtils.replaceEach(html, tags.toArray(new String[tags.size()]), s_tags.toArray(new String[s_tags.size()]));                 
        html = html.replaceAll("\\</p>(?i)", "\n");  
        html = html.replaceAll("\\<[^>]+>", "");  
        html = ExStringUtils.replaceEach(html,s_tags.toArray(new String[s_tags.size()]),tags.toArray(new String[tags.size()]));  
        html = html.replaceAll("\\ ", " ");  
        return html.trim();  
    }  




猜你喜欢

转载自blog.csdn.net/mattdong0106/article/details/44020619
今日推荐