Android相关状态工具类

25 篇文章 0 订阅

Android学习开发用的相关状态工具类 

package xxx.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Binder;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jaydenxiao.common.commonutils.LogUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import xxx.app.AppApplication;

/**
 * <p>
 * Title: xxx客户端_[子系统统名]_[工具]
 * </p>
 * <p>
 * Description: [相关状态工具类]
 * </p>
 *
 * @author BGL
 * @author (lastest modification by $Author$)
 * @version $Revision$  2019-xx-xx
 * @since 2019
 */
public class AppStatusUtils {

    private static final String TAG = "AppStatusUtils";

    /**
     * 获取当前版本号
     * @return 版本号 如:101
     */
    public static int getVersionNum() {
        String version = "0";
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = AppApplication.getAppContext().getPackageManager();
            // getPackageName()是你当前类的包名,0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(AppApplication.getAppContext().getPackageName(),0);
            version = packInfo.versionName;
        } catch (Exception e) {
            LogUtils.loge("getVersionNum Exception:"+e.getMessage());
            version = "0";
        }
        return Integer.valueOf(version.replaceAll("\\.", ""));
    }

    /**
     *
     * 判断某activity是否处于栈顶
     * @return true在栈顶 false不在栈顶
     */
    public static boolean isActivityTop(Class cls,Context context){
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(cls.getName());
    }

    /**
     * 方法描述:判断某一Service是否正在运行
     *
     * @param context
     *            上下文
     * @param serviceName
     *            Service的全路径: 包名 + service的类名
     * @return true 表示正在运行,false 表示没有运行
     */
    public static boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = am
                .getRunningServices(200);
        if (runningServiceInfos.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningServiceInfo serviceInfo : runningServiceInfos) {
            if (serviceInfo.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 返回app运行状态 1:程序在前台运行 2:程序在后台运行 3:程序未启动 注意:需要配置权限<uses-permission
     * android:name="android.permission.GET_TASKS" />
     */
    public static int getAppSatus(Context context, String pageName) {

        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(20);

        // 判断程序是否在栈顶
        if (list.get(0).topActivity.getPackageName().equals(pageName)) {
            return 1;
        } else {
            // 判断程序是否在栈里
            for (ActivityManager.RunningTaskInfo info : list) {
                if (info.topActivity.getPackageName().equals(pageName)) {
                    return 2;
                }
            }
            return 3;// 栈里找不到,返回3
        }
    }

    /**
     * 获得属于桌面的应用的应用包名称
     *
     * @return 返回包含所有包名的字符串列表
     */
    public static List<String> getHomes(Context context) {
        List<String> names = new ArrayList<String>();
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resolveInfos) {
            names.add(resolveInfo.activityInfo.packageName);
        }
        return names;
    }

    /**
     * 判断当前界面是否是桌面
     */
    public static boolean isHome(Context context) {
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        return getHomes(context).contains(rti.get(0).topActivity.getPackageName());
    }

    /**
     * Android 检查悬浮窗权限是否打开
     * 判断 悬浮窗口权限是否打开
     * @param context
     * @return true 允许  false禁止
     */
    public static boolean checkAlertWindowsPermission(Context context) {
        try {
            Object object = context.getSystemService(Context.APP_OPS_SERVICE);
            if (object == null) {
                return false;
            }
            Class localClass = object.getClass();
            Class[] arrayOfClass = new Class[3];
            arrayOfClass[0] = Integer.TYPE;
            arrayOfClass[1] = Integer.TYPE;
            arrayOfClass[2] = String.class;
            Method method = localClass.getMethod("checkOp", arrayOfClass);
            if (method == null) {
                return false;
            }
            Object[] arrayOfObject1 = new Object[3];
            arrayOfObject1[0] = 24; // AppOpsManager.OP_SYSTEM_ALERT_WINDOW
            arrayOfObject1[1] = Binder.getCallingUid();
            arrayOfObject1[2] = context.getPackageName();
            int m = ((Integer) method.invoke(object, arrayOfObject1));
            return m == AppOpsManager.MODE_ALLOWED;
        } catch (Exception ex) {

        }
        return false;
    }

    /**
     * 设置GIF动态图
     * @param context
     * @param imageView
     * @param resourceId
     */
    public static void setPlayImgAsGif(Context context, ImageView imageView, Integer resourceId) {
        Glide.with(context).load(resourceId).asGif()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .crossFade()
                .into(imageView);
    }

    public static void setNormalImg(Context context, ImageView imageView, Integer resourceId) {

        Glide.with(context).load(resourceId)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .crossFade()
                .into(imageView);
    }

    /**
     * 获取状态栏高度
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    /**
     * 设置TextView显示字数多余省略号显示
     * @param targetView  TextView
     * @param limitNum    限制显示字数个数
     * @param possition   省略号表明位置 END、START、MIDDLE、MARQUEE(跑马灯)
     * @param maxLines    控制显示几行数据
     * @param text        显示内容
     */
    public static void showLimitTextValue(TextView targetView, int limitNum, String possition, int maxLines, String text) {
        if (null != targetView) {
            targetView.setEllipsize(TextUtils.TruncateAt.valueOf(possition));
            targetView.setMaxEms(limitNum);
            targetView.setMaxLines(maxLines);
            targetView.setText(text);
        }
    }

    /**
     *
     * 给TextView设置左或右侧背景图
     * @param context
     * @param id
     * @param view
     * @param drawableLefOrRight
     * @param paddingNum
     */
    public static void setDrawableImg2LeftOrRight(Context context, @DrawableRes int id, TextView view, String drawableLefOrRight, int paddingNum) {
        Drawable drawable = context.getResources().getDrawable(id);

        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());

        if ("LEFT".equalsIgnoreCase(drawableLefOrRight)) { // 加在左侧
            view.setCompoundDrawables(drawable,null,null,null);
        } else {
            view.setCompoundDrawables(null,null,drawable,null);
        }

        view.setCompoundDrawablePadding(paddingNum);
    }

    /**
     * 参数:maxLines 要限制的最大行数
     * 参数:content  指TextView中要显示的内容
     */
    public static void setMaxEcplise(final TextView mTextView, final int maxLines, final String content) {

        ViewTreeObserver observer = mTextView.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@
                Override
        public void onGlobalLayout() {
            mTextView.setText(content);
            if (mTextView.getLineCount() > maxLines) {
                int lineEndIndex = mTextView.getLayout().getLineEnd(maxLines - 1);
               
                String text = content.subSequence(0, lineEndIndex - 3) + "...";
                mTextView.setText(text);
            } else {
                removeGlobalOnLayoutListener(mTextView.getViewTreeObserver(), this);
            }
        }
        });
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值