`
222xiaohuan
  • 浏览: 50625 次
  • 性别: Icon_minigender_2
  • 来自: 苏州
社区版块
存档分类
最新评论

android app develop utils

 
阅读更多
/*
 * Copyright (C) 2012 www.apkdv.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lengyue.apkdv.golddemo;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

// TODO: Auto-generated Javadoc

/**
 * © 2012 apkdv.com
 * 名称:AbAppUtil.java
 * 描述:应用工具类.
 *
 * @author LengYue
 * @version v1.0
 * @date:2013-11-10 下午11:52:13
 */
public class DvAppUtil {


    /**
     * 描述:打开并安装文件.
     *
     * @param context the context
     * @param file    apk文件路径
     */
public static void installApk(Context context, File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 描述:卸载程序.
     *
     * @param context     the context
     * @param packageName 包名
     */
public static void uninstallApk(Context context, String packageName) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        Uri packageURI = Uri.parse("package:" + packageName);
        intent.setData(packageURI);
        context.startActivity(intent);
    }


    /**
     * 用来判断服务是否运行.
     *
     * @param ctx       the ctx
     * @param className 判断的服务名字 "com.xxx.xx..XXXService"
     * @return true 在运行 false 不在运行
     */
public static boolean isServiceRunning(Context ctx, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningServiceInfo> servicesList = activityManager.getRunningServices(Integer.MAX_VALUE);
        Iterator<RunningServiceInfo> l = servicesList.iterator();
        while (l.hasNext()) {
            RunningServiceInfo si = (RunningServiceInfo) l.next();
            if (className.equals(si.service.getClassName())) {
                isRunning = true;
            }
        }
        return isRunning;
    }

    /**
     * 停止服务.
     *
     * @param ctx       the ctx
     * @param className the class name
     * @return true, if successful
     */
public static boolean stopRunningService(Context ctx, String className) {
        Intent intent_service = null;
        boolean ret = false;
        try {
            intent_service = new Intent(ctx, Class.forName(className));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (intent_service != null) {
            ret = ctx.stopService(intent_service);
        }
        return ret;
    }


    /**
     * Gets the number of cores available in this device, across all processors.
     * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
     *
     * @return The number of cores, or 1 if failed to get result
     */
public static int getNumCores() {
        try {
            //Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
            //Filter to only list the devices we care about
File[] files = dir.listFiles(new FileFilter() {

                @Override
public boolean accept(File pathname) {
                    //Check if filename is "cpu", followed by a single digit number
if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                        return true;
                    }
                    return false;
                }

            });
            //Return the number of cores (virtual CPU devices)
return files.length;
        } catch (Exception e) {
            //Default to return 1 core
return 1;
        }
    }


    /**
     * 描述:判断网络是否有效.
     *
     * @param context the context
     * @return true, if is network available
     */
public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * Gps是否打开
     * 需要<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />权限
     *
     * @param context the context
     * @return true, if is gps enabled
     */
public static boolean isGpsEnabled(Context context) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * wifi是否打开.
     *
     * @param context the context
     * @return true, if is wifi enabled
     */
public static boolean isWifiEnabled(Context context) {
        ConnectivityManager mgrConn = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager mgrTel = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
                .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
                .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
    }

    /**
     * 判断当前网络是否是wifi网络.
     *
     * @param context the context
     * @return boolean
     */
public static boolean isWifi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    /**
     * 判断当前网络是否是移动数据网络.
     *
     * @param context the context
     * @return boolean
     */
public static boolean isMobile(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
&& activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            return true;
        }
        return false;
    }

    /**
     * 导入数据库.
     *
     * @param context the context
     * @param dbName  the db name
     * @param rawRes  the raw res
     * @return true, if successful
     */
public static boolean importDatabase(Context context, String dbName, int rawRes) {
        int buffer_size = 1024;
        InputStream is = null;
        FileOutputStream fos = null;
        boolean flag = false;

        try {
            String dbPath = "/data/data/" + context.getPackageName() + "/databases/" + dbName;
            File dbfile = new File(dbPath);
            //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
if (!dbfile.exists()) {
                //欲导入的数据库
if (!dbfile.getParentFile().exists()) {
                    dbfile.getParentFile().mkdirs();
                }
                dbfile.createNewFile();
                is = context.getResources().openRawResource(rawRes);
                fos = new FileOutputStream(dbfile);
                byte[] buffer = new byte[buffer_size];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }
        return flag;
    }

    /**
     * 获取屏幕尺寸与密度.
     *
     * @param context the context
     * @return mDisplayMetrics
     */
public static DisplayMetrics getDisplayMetrics(Context context) {
        Resources mResources;
        if (context == null) {
            mResources = Resources.getSystem();

        } else {
            mResources = context.getResources();
        }
        //DisplayMetrics{density=1.5, width=480, height=854, scaledDensity=1.5, xdpi=160.421, ydpi=159.497}
        //DisplayMetrics{density=2.0, width=720, height=1280, scaledDensity=2.0, xdpi=160.42105, ydpi=160.15764}
DisplayMetrics mDisplayMetrics = mResources.getDisplayMetrics();
        return mDisplayMetrics;
    }

    /**
     * 打开键盘.
     *
     * @param context the context
     */
public static void showSoftInput(Context context) {
        InputMethodManager inputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 关闭键盘事件.
     *
     * @param context the context
     */
public static void closeSoftInput(Context context) {
        InputMethodManager inputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && ((Activity) context).getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 获取包信息.
     *
     * @param context the context
     */
public static PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;
        try {
            String packageName = context.getPackageName();
            info = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }


}
分享到:
评论

相关推荐

    dnn_app_utils_v2.py 和 datasets

    coursera的吴恩达的课编程练习所需的所需包和数据,可以方便学员自己在本地练习

    Android系统编译canutils

    内含移植成功的canutils源码+libsocketcan源码,说明内已经写好编译方法和编译...需要换版本可以直接替换源码,源码使用Android.bp编译canutils(注意Android 7以后的系统才支持Android.bp,否则需要自己改编译脚本)。

    android develop utils

    android中一些常用的工具类

    Python库 | app_utils-0.1a4.tar.gz

    资源分类:Python库 所属语言:Python 资源全名:app_utils-0.1a4.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    Android代码-android-utils

    Android-Utils  Android Library facilitating some very common functionalities in the form of utility classes for Android ...

    Android代码-Utils Android

    Android Commons aims to provide quick, easy and ready to use set of functionalities and utilites. It consist of various method for Bitmap Image Scaling, Application, Network, I/O , SQLite database and...

    android好用的utils集合

    很多的工具类,平时开发的用到的工具类集合,直接复制粘贴就好,挺好用的

    吴EW老师 dnn_app_utils_v2资源

    coursera的吴恩达的课编程练习,一次神经网络所需的所有函数定义

    android-ui-utils,从code.google.com/p/android-ui-utils自动导出.zip

    android-ui-utils,从code.google.com/p/android-ui-utils自动导出.zip

    Android常用工具类Utils

    android开发中常用的工具类封装,帮助开发者更轻松的实现如系统,图片,弹框,toast,文件,日志,通知栏,sp,线程管理,时间日期等等。

    Android代码-Utils

    Utils-android开发轻武器库 JUtils:小功能集合 JActivityManager:Activity的管理类。保持所有存在activity引用 JFileManager:data目录下文件管理 JTimeTransform:时间格式转换器 添加依赖 compile '...

    alsa-lib alsa-utils android环境编译

    alsa-lib alsa-utils 在android编译成功 warning: shared library text segment is not shareable error: treating warnings as errors 编译器的选项要加上 --no-fatal-warnings 可无论怎么加, 加到那儿都变成了...

    uni-app 自己封装的utils.js

    uni-app 自己封装的utils.js 常用工具类(封装的ajax,上传,查看文档,富文本解析)

    android验证码倒计时Utils

    一行代码实现安卓验证码发送按钮倒计时功能,绝对靠谱

    AndroidUtils

    每次新开一个项目的时候,当用到什么基础工具类的时候,我们获取会去自己写,很多时候...今天我就把我们Android开发中会常用到的工具类做个总结。以后工作中再用到的话,就直接去自己仓库中找就行了,提高了工作效率。

    Android代码-OkHttp3Utils

    爱生活,爱学习,更爱做代码的搬运工,分类查找更方便请下载黑马助手app 使用步骤 1. 在project的build.gradle添加如下代码(如下图) allprojects { repositories { ... maven { url "https://jitpack.io" } } } ...

    Android代码-android-chunk-utils

    Android Chunk format reader/writer This project contains classes extracted from the android-arscblamer project that deal with reading and writing the resource table and compiled XML files present in ...

    react-native-in-app-utils:React式包装器,用于处理应用内付款

    react-native-in-app-utils React原生包装器,用于处理iOS中的应用内购买。 突破性变革 由于RN 0.40+的重大更改,从npm安装时请使用此库的版本5或更高版本。 笔记 您需要一个Apple Developer帐户才能使用应用程序内...

    Android-utils

    NULL 博文链接:https://jerry--xie.iteye.com/blog/1612191

Global site tag (gtag.js) - Google Analytics