This commit is contained in:
2019-12-25 11:28:10 +08:00
commit cdd3d43ae3
87 changed files with 16373 additions and 0 deletions

View File

@@ -0,0 +1,454 @@
package com.info.sn.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import com.info.sn.R;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class ApkUtils {
public static synchronized boolean getRootAhth() {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes("exit\n");
os.flush();
int exitValue = process.waitFor();
if (exitValue == 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
Log.e("*** DEBUG ***", "Unexpected error - Here is what I know: "
+ e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openApp(Context context, View view) {
try {
Intent intent = context.getPackageManager().getLaunchIntentForPackage((String) view.getTag(R.string.download_btn_had));
context.startActivity(intent);
} catch (Exception e) {
Toast.makeText(context, R.string.open_app_fail, Toast.LENGTH_LONG).show();
}
return;
}
public static void openApp(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
/**
* 安装一个apk文件
*/
public static void install(Context context, File uriFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// 由于没有在Activity环境下启动Activity,设置下面的标签
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
//参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件
Uri apkUri =
FileProvider.getUriForFile(context, "com.info.sn.fileprovider", uriFile);
//添加这一句表示对目标应用临时授权该Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(uriFile),
"application/vnd.android.package-archive");
}
context.startActivity(intent);
}
/**
* 卸载一个app
*/
public static void uninstall(Context context, String packageName) {
//通过程序的包名创建URI
Uri packageURI = Uri.parse("package:" + packageName);
//创建Intent意图
Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
//执行卸载程序
context.startActivity(intent);
}
/**
* 检查手机上是否安装了指定的软件
*/
public static boolean isAvailable(Context context, String packageName) {
// 获取packagemanager
final PackageManager packageManager = context.getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
// 用于存储所有已安装程序的包名
List<String> packageNames = new ArrayList<>();
// 从pinfo中将包名字逐一取出压入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
// 判断packageNames中是否有目标程序的包名有TRUE没有FALSE
return packageNames.contains(packageName);
}
/**
* 检查手机上是否安装了指定的软件
*/
public static boolean isAvailable(Context context, File file) {
return isAvailable(context, getPackageName(context, file.getAbsolutePath()));
}
/**
* 根据文件路径获取包名
*/
public static String getPackageName(Context context, String filePath) {
PackageManager packageManager = context.getPackageManager();
PackageInfo info = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
return appInfo.packageName; //得到安装包名称
}
return null;
}
/**
* 从apk中获取版本信息
*/
public static String getChannelFromApk(Context context, String channelPrefix) {
//从apk包中获取
ApplicationInfo appinfo = context.getApplicationInfo();
String sourceDir = appinfo.sourceDir;
//默认放在meta-inf/里, 所以需要再拼接一下
String key = "META-INF/" + channelPrefix;
String ret = "";
ZipFile zipfile = null;
try {
zipfile = new ZipFile(sourceDir);
Enumeration<?> entries = zipfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName();
if (entryName.startsWith(key)) {
ret = entryName;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zipfile != null) {
try {
zipfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] split = ret.split(channelPrefix);
String channel = "";
if (split.length >= 2) {
channel = ret.substring(key.length());
}
return channel;
}
public static void installRx(final Context context, final String packageName, final String filePath) {
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
File file = new File(filePath);
if (filePath == null || filePath.length() == 0 || file == null) {
Log.e("fanhuitong", "errormesg=========" + " 空啊 ");
subscriber.onNext(0);
return;
}
// String[] args = { "pm", "install", "-r", filePath };
String[] args = {"pm", "install", "-i", "com.colorflykids", "--user", "0", filePath};
// String argss = "pm install -i " + "com.colorflykids" + " --user 0 " + filePath;
Log.e("fanhuitong", "argss====" + args);
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
process = processBuilder.start();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
Log.e("mjhseng", "successResult----------" + s);
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
Log.e("mjhseng", "errorResult----------" + s);
errorMsg.append(s);
}
} catch (IOException e1) {
Log.e("fanhuitong", "IOException e1)----------" + e1.toString());
e1.printStackTrace();
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e1) {
Log.e("fanhuitong", "IOException e11)---------" + e1.toString());
e1.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
subscriber.onNext(2);
} else {
Log.e("fanhuitong", "errormesg=========" + errorMsg.toString());
subscriber.onNext(1);
}
}
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Integer>() {
@Override
public void onNext(Integer value) {
if (value == 2) {
//安装成功
Utils.showToast(context, "安装成功");
Log.e("fanhuitong", "-----------安装成功-----------");
} else {
//安装错误
Log.e("fanhuitong", "------------安装错误-----------");
Utils.showToast(context, "安装失败");
}
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//安装错误
}
});
}
// public static void installApp(final String path, final String packageNames){
// File apkFile = new File(path);
// try {
// Class<?> clazz = Class.forName("android.os.ServiceManager");
// Method method_getService = clazz.getMethod("getService", String.class);
// IBinder bind = (IBinder) method_getService.invoke(null, "package");
// IPackageManager iPm = IPackageManager.Stub.asInterface(bind);
// iPm.installPackage(Uri.fromFile(apkFile),null, 2, apkFile.getName());
// Log.e("fanhuitong", "安装成功");
// } catch (Exception e) {
// e.printStackTrace();
// Log.e("fanhuitong", "安装失败");
// }
// }
//使用系统签名
public static void installApkInSilence(String installPath, String packageName) {
ToastUtil.show("正在安装应用...");
Class<?> pmService;
Class<?> activityTherad;
Method method;
try {
activityTherad = Class.forName("android.app.ActivityThread");
Class<?> paramTypes[] = getParamTypes(activityTherad, "getPackageManager");
method = activityTherad.getMethod("getPackageManager", paramTypes);
Object PackageManagerService = method.invoke(activityTherad);
pmService = PackageManagerService.getClass();
Class<?> paramTypes1[] = getParamTypes(pmService, "installPackageAsUser");
method = pmService.getMethod("installPackageAsUser", paramTypes1);
method.invoke(PackageManagerService, installPath, null, 0x00000040, packageName, getUserId(Binder.getCallingUid()));//getUserId
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public static void deleteApkInSilence(String packageName) {
Class<?> pmService;
Class<?> activityTherad;
Method method;
try {
activityTherad = Class.forName("android.app.ActivityThread");
Class<?> paramTypes[] = getParamTypes(activityTherad, "getPackageManager");
method = activityTherad.getMethod("getPackageManager", paramTypes);
Object PackageManagerService = method.invoke(activityTherad);
pmService = PackageManagerService.getClass();
Class<?> paramTypes1[] = getParamTypes(pmService, "deletePackageAsUser");
method = pmService.getMethod("deletePackageAsUser", paramTypes1);
method.invoke(PackageManagerService, packageName, null, getUserId(Binder.getCallingUid()), 0x00000040);//getUserId
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private static Class<?>[] getParamTypes(Class<?> cls, String mName) {
Class<?> cs[] = null;
Method[] mtd = cls.getMethods();
for (int i = 0; i < mtd.length; i++) {
if (!mtd[i].getName().equals(mName)) {
continue;
}
cs = mtd[i].getParameterTypes();
}
return cs;
}
public static final int PER_USER_RANGE = 100000;
public static int getUserId(int uid) {
return uid / PER_USER_RANGE;
}
public static boolean checkIsUpdate(Context context, String packageName, int versionCode) {
PackageManager packageManager = context.getPackageManager();
boolean update = false;
PackageInfo packageInfo = null;
try {
packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
int code = packageInfo.versionCode;
update = versionCode > code;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
// LogUtils.e("NameNotFoundException", e.getMessage());
update = false;
}
return update;
}
synchronized public static PackageInfo getPackageInfo(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.e("getPackageInfo", packageName + ":" + e.getMessage());
}
return packageInfo;
}
synchronized public static String getApplicationName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
PackageInfo packageInfo = null;
String name = "";
try {
packageInfo = pm.getPackageInfo(packageName, 0);
name = pm.getApplicationLabel(packageInfo.applicationInfo).toString();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Log.e("getPackageInfo", packageName + ":" + e.getMessage());
}
return name;
}
public static void installApk(Activity activity, File newApkFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String type = "application/vnd.android.package-archive";
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(activity, "com.info.sn.fileprovider", newApkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(newApkFile);
}
intent.setDataAndType(uri, type);
activity.startActivity(intent);
}
public static void installApk(Context context, File newApkFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String type = "application/vnd.android.package-archive";
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, "com.info.sn.fileprovider", newApkFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(newApkFile);
}
intent.setDataAndType(uri, type);
context.startActivity(intent);
}
}

View File

@@ -0,0 +1,34 @@
package com.info.sn.utils;
/**
* Created by Administrator on 2017/1/10.
*/
public class AppUpdateInfo {
private String packageName;
private String version;
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
@Override
public String toString() {
return "AppUpdateInfo{" +
"packageName='" + packageName + '\'' +
", version='" + version + '\'' +
'}';
}
}

View File

@@ -0,0 +1,146 @@
package com.info.sn.utils;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AppsManagerUtils {
public static AppUpdateInfo getUpAppsByPackageName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
AppUpdateInfo appInfo = new AppUpdateInfo();
try {
PackageInfo packinfo = pm.getPackageInfo(packageName, 0);
appInfo.setPackageName(packageName);
appInfo.setVersion(packinfo.versionName);
if (packinfo.versionName == null || packinfo.versionName.equals("")) {
appInfo.setVersion(packinfo.versionCode + "");
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return appInfo;
}
public static LocalAppInfo getAppsByPackageName(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
List<LocalAppInfo> appInfos = new ArrayList<LocalAppInfo>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通过查询获得所有ResolveInfo对象.
List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo info : infos) {
// 不列出系统应用
String pkg = info.activityInfo.packageName;
if (pkg.equals(packageName)) {
extractedAppInfo(pm, appInfos, info);
}
}
return appInfos.get(0);
}
public static List<AppUpdateInfo> getUpadteApps(Context context) {
PackageManager pm = context.getPackageManager();
List<AppUpdateInfo> appInfos = new ArrayList<AppUpdateInfo>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通过查询获得所有ResolveInfo对象.
List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo info : infos) {
// 不列出系统应用
String pkg = info.activityInfo.packageName;
if (!isSystemApp(context, pkg)) {
PackageInfo packageInfo = null;
AppUpdateInfo appInfo = new AppUpdateInfo();
appInfo.setPackageName(info.activityInfo.packageName);
try {
packageInfo = pm.getPackageInfo(info.activityInfo.packageName, 0);
appInfo.setVersion(packageInfo.versionName);
if (packageInfo.versionName == null || packageInfo.versionName.equals("")) {
appInfo.setVersion(packageInfo.versionCode + "");
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
appInfos.add(appInfo);
}
}
return appInfos;
}
public static List<LocalAppInfo> getUserApps(Context context) {
PackageManager pm = context.getPackageManager();
List<LocalAppInfo> appInfos = new ArrayList<LocalAppInfo>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通过查询获得所有ResolveInfo对象.
List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo info : infos) {
// 不列出系统应用
String pkg = info.activityInfo.packageName;
if (!isSystemApp(context, pkg)) {
extractedAppInfo(pm, appInfos, info);
}
}
return appInfos;
}
private static void extractedAppInfo(PackageManager pm,
List<LocalAppInfo> appInfos, ResolveInfo info) {
PackageInfo packageInfo = null;
LocalAppInfo appInfo = new LocalAppInfo();
appInfo.setIcon(info.activityInfo.loadIcon(pm));
appInfo.setAppName(info.activityInfo.loadLabel(pm).toString());
appInfo.setPackageName(info.activityInfo.packageName);
try {
packageInfo = pm.getPackageInfo(info.activityInfo.packageName, 0);
appInfo.setVersion(packageInfo.versionName);
if (packageInfo.versionName == null || packageInfo.versionName.equals("")) {
appInfo.setVersion(packageInfo.versionCode + "");
}
String appInstallDir = info.activityInfo.applicationInfo.publicSourceDir;
int size = Integer.valueOf((int) new File(appInstallDir).length());
appInfo.setSize(size);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
appInfos.add(appInfo);
}
public static boolean isSystemApp(Context context, String pkg) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(pkg, 0);
if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
if (pkg.equals(context.getPackageName())) {
return true;
} else {
//第三方应用
return false;
}
} else {
//系统应用
return true;
}
} catch (NameNotFoundException e) {
e.printStackTrace();
return true;
}
}
}

View File

@@ -0,0 +1,28 @@
package com.info.sn.utils;
public class CommonData {
public static final String MAJOR_ACTION = "MAJOR_ACTION";
public static final String FLAG_FIRST_ENTER = "first_enter";
public static final String SP_USER_ID = "user_ID";
public static final String SP_USER_PHONE = "user_phone";
public static final String SP_USER_NAME = "user_name";
public static final String SP_USER_IDCARD = "user_idcard";
public static final String SP_USER_PASSWORD = "user_pass";
public static final String SP_RECOMMEND_PHONE = "recommend_phone";
public static final String SP_RECOMMEND_NAME = "sup_name";
public static final String SP_USER_LEVEL = "user_level";
public static final String SP_ISLOGINED = "user_islogined";
public static final String NEXT_PAGE = "next_page";
public static final String BANK_NAME = "bank_name";
public static final String OPERATOR_NAME = "bank_name";
public static final String PRODUCT_LINK = "product_link";
public static final String PRODUCT_NAME = "product_name";
}

View File

@@ -0,0 +1,144 @@
package com.info.sn.utils;
import android.graphics.drawable.Drawable;
public class LocalAppInfo {
public static final int DOWNLOAD_STATUS_NORMAL = 0;
public static final int DOWNLOAD_STATUS_DOWNLOADING = 1;
public static final int DOWNLOAD_STATUS_PAUSE = 2;
private Drawable icon;
private String iconUrl = "";
private String appName;
private String packageName;
private String version;
private String latestVersion = "";
private int size;
private String latestSize;
private String downLoadUrl;
private int dowloadStatus = DOWNLOAD_STATUS_NORMAL;
private String tip;
private int id;
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getLatestVersion() {
return latestVersion;
}
public void setLatestVersion(String latestVersion) {
this.latestVersion = latestVersion;
}
public String getLatestSize() {
return latestSize;
}
public void setLatestSize(String latestSize) {
this.latestSize = latestSize;
}
public String getDownLoadUrl() {
return downLoadUrl;
}
public void setDownLoadUrl(String downLoadUrl) {
this.downLoadUrl = downLoadUrl;
}
public int getDowloadStatus() {
return dowloadStatus;
}
public void setDowloadStatus(int dowloadStatus) {
this.dowloadStatus = dowloadStatus;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "AppUpdateInfo{" +
"packageName='" + packageName + '\'' +
", version='" + version + '\'' +
'}';
}
public boolean equals(Object obj) {
if (this == obj) //传入的对象就是它自己如s.equals(s);肯定是相等的;
return true;
if (obj == null) //如果传入的对象是空,肯定不相等
return false;
if (getClass() != obj.getClass()) //如果不是同一个类型的如Studnet类和Animal类
//也不用比较了,肯定是不相等的
return false;
LocalAppInfo other = (LocalAppInfo) obj;
if (packageName == null) {
if (other.packageName != null)
return false;
} else if (!packageName.equals(other.packageName)) //如果name属性相等则相等
return false;
return true;
}
}

View File

@@ -0,0 +1,40 @@
package com.info.sn.utils;
import android.util.Log;
import com.info.sn.BuildConfig;
public class LogUtils {
static boolean isDebug = BuildConfig.LOG_DEBUG;
// static boolean isDebug = BuildConfig.LOG_DEBUG;
public static void v(String tag, String msg) {
if (isDebug) {
Log.v(tag, msg);
}
}
public static void d(String tag, String msg) {
if (isDebug) {
Log.d(tag, msg);
}
}
public static void i(String tag, String msg) {
if (isDebug) {
Log.i(tag, msg);
}
}
public static void w(String tag, String msg) {
if (isDebug) {
Log.w(tag, msg);
}
}
public static void e(String tag, String msg) {
if (isDebug) {
Log.e(tag, msg);
}
}
}

View File

@@ -0,0 +1,198 @@
package com.info.sn.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.widget.ImageView;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
/**
* 作者 mjsheng
* 日期 2018/10/9 18:41
* 邮箱 278359328@qq.com
* 来自:
*/
public class SPUtils {
/**
* 保存在手机里面的文件名
*/
public static final String FILE_NAME = "share_data";
/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*/
public static void put(Context context, String key, Object object) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
editor.putFloat(key, (Float) object);
} else if (object instanceof Long) {
editor.putLong(key, (Long) object);
} else {
editor.putString(key, object.toString());
}
SharedPreferencesCompat.apply(editor);
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*/
public static Object get(Context context, String key, Object defaultObject) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
/**
* 移除某个key值已经对应的值
*/
public static void remove(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
SharedPreferencesCompat.apply(editor);
}
/**
* 清除所有数据
*/
public static void clear(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
SharedPreferencesCompat.apply(editor);
reductFirstEnter(context);
}
//还原状态firstEnter信息
private static void reductFirstEnter(Context context){
put(context, CommonData.FLAG_FIRST_ENTER,CommonData.FLAG_FIRST_ENTER);
}
/**
* 查询某个key是否已经存在
*/
public static boolean contains(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.contains(key);
}
/**
* 返回所有的键值对
*/
public static Map<String, ?> getAll(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.getAll();
}
/**
* 保存图片到SharedPreferences
*
* @param mContext
* @param imageView
*/
public static void putImage(Context mContext, String key, ImageView imageView) {
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
// 将Bitmap压缩成字节数组输出流
ByteArrayOutputStream byStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byStream);
// 利用Base64将我们的字节数组输出流转换成String
byte[] byteArray = byStream.toByteArray();
String imgString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
// 将String保存shareUtils
SPUtils.put(mContext, key, imgString);
}
/**
* 从SharedPreferences读取图片
*
* @param mContext
* @param imageView
*/
public static Bitmap getImage(Context mContext, String key, ImageView imageView) {
String imgString = (String) SPUtils.get(mContext, key, "");
if (!imgString.equals("")) {
// 利用Base64将我们string转换
byte[] byteArray = Base64.decode(imgString, Base64.DEFAULT);
ByteArrayInputStream byStream = new ByteArrayInputStream(byteArray);
// 生成bitmap
return BitmapFactory.decodeStream(byStream);
}
return null;
}
/**
* 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
*/
private static class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod();
/**
* 反射查找apply的方法
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private static Method findApplyMethod() {
try {
Class clz = SharedPreferences.Editor.class;
return clz.getMethod("apply");
} catch (NoSuchMethodException e) {
}
return null;
}
/**
* 如果找到则使用apply执行否则使用commit
*/
public static void apply(SharedPreferences.Editor editor) {
try {
if (sApplyMethod != null) {
sApplyMethod.invoke(editor);
return;
}
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
editor.commit();
}
}
}

View File

@@ -0,0 +1,24 @@
package com.info.sn.utils;
import android.app.ActivityManager;
import android.content.Context;
import com.info.sn.MyApplication;
public class ServiceAliveUtils {
public static boolean isServiceAlice() {
boolean isServiceRunning = false;
ActivityManager manager =
(ActivityManager) MyApplication.getInstance().getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
if (manager == null) {
return true;
}
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("demo.lgm.com.keepalivedemo.service.DownloadService".equals(service.service.getClassName())) {
isServiceRunning = true;
}
}
return isServiceRunning;
}
}

View File

@@ -0,0 +1,65 @@
package com.info.sn.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import com.info.sn.BuildConfig;
/**
* Created by haoge on 2017/3/2.
*/
public class ToastUtil {
static Handler mainHandler = new Handler(Looper.getMainLooper());
static Toast toast;
@SuppressLint("ShowToast")
public static void init(Context context) {
toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
debugToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
}
public static void show(final String msg) {
mainHandler.post(new Runnable() {
@Override
public void run() {
if (toast != null) {
toast.setText(msg);
toast.show();
}
}
});
}
// public static void showInCenter(String msg) {
// mainHandler.post(() -> {
// if (toast != null) {
// toast.setGravity(Gravity.CENTER, 0, 0);
// toast.setText(msg);
// toast.show();
// }
// });
// }
static Handler debugHandler = new Handler(Looper.getMainLooper());
static Toast debugToast;
public static void debugShow(final String msg) {
mainHandler.post(new Runnable() {
@Override
public void run() {
if (BuildConfig.LOG_DEBUG) {
if (toast != null) {
toast.setText(msg);
toast.show();
}
}
}
});
}
}

View File

@@ -0,0 +1,864 @@
package com.info.sn.utils;
import android.annotation.SuppressLint;
import android.app.admin.DevicePolicyManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.info.sn.MyApplication;
import com.info.sn.R;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Utils {
public static final String PACKAGE = "appstore";
public static final String DOWNLOAD_STARTALL_ACTION = PACKAGE + "_startall"; // 开始所有任务
public static final String DOWNLOAD_DELETE_UPDATE_ACTION = PACKAGE + "_download_update_delete"; // 删除应用更新文件
public static final String DOWNLOAD_DELETEALL_ACTION = PACKAGE + "_deleteall_alltask"; // 删除所有任务
public static final String DOWNLOAD_ALLTASK_ACTION = PACKAGE + "_download_alltask"; // 获取所有任务
public static final String DOWNLOAD_START_ACTION = PACKAGE + "_download_start"; // 下载标识
public static final String DOWNLOAD_STOP_ACTION = PACKAGE + "_download_stop"; // 暂停标识
public static final String DOWNLOAD_DELETE_PACKAGENAME_ACTION = PACKAGE + "_download_packagename_delete"; // 删除标识 根据包名
public static final String DOWNLOAD_DELETE_URL_ACTION = PACKAGE + "_download_url_delete"; // 删除标识 根据下载地址
public static final String DOWNLOAD_INITIALIZE_ACTION = PACKAGE + "_download_initialize"; // item初始化状态
public static final String DOWNLOAD_PACKAGENAME_ACTION = PACKAGE + "_download_packagename"; // item初始化状态 包名
public static final String DOWNLOAD_SERVICE_ACTION = PACKAGE + "_download_service"; // 下载状态回调服务
public static final String DOWNLOAD_ALLSERVICE_ACTION = PACKAGE + "_download_allservice"; // 返回所有下载任务
public static final String DOWNLOAD_NEWSERVICE_ACTION = PACKAGE + "_download_newservice"; // 一个新的下载任务
// JPush 推送消息
public static final String MESSAGE_RECEIVED_ACTION = "com.appstore.jpushdemo.MESSAGE_RECEIVED_ACTION";
public static final String KEY_TITLE = "title"; // 消息标题
public static final String KEY_MESSAGE = "message"; // 消息内容
public static final String KEY_EXTRAS = "extras"; // 消息内容类型
public static final String KEY_TYPE = "type"; // 消息内容类型
public static final String ACTION_PACKAGE_REPLACED = PACKAGE + "PACKAGE_REPLACED"; // 替换应用
public static final String ACTION_PACKAGE_REMOVED = PACKAGE + "PACKAGE_REMOVED"; // 卸载应用
public static final String ACTION_PACKAGE_ADDED = PACKAGE + "PACKAGE_ADDED"; // 安装应用
// public static int[] babyImage = {R.drawable.language, R.drawable.habit, R.drawable.knowledge, R.drawable.security, R.drawable.promotion};
// public static int[] childImage = {R.drawable.yuwen, R.drawable.shuxue, R.drawable.yingyu, R.drawable.qingshang, R.drawable.yishu, R.drawable.promotion};
// public static int[] youngImage = {R.drawable.yuwen, R.drawable.shuxue, R.drawable.yingyu, R.drawable.promotion};
// 学习日志上传标识
public static final String APP_LRARNLOG = "com.colorflykids.alarm";
// 学习日志下载标识
public static final String APP_DOWNLOADLEARNLOG = "com.colorflykids.downloadlearnlog";
// 账号注销标识
public static final String APP_USERLOGOUT = "com.colorflykids.userlogout";
public static final String UPDATE_SYSTEMUI = "cn.colorflykids.UPDATE_SYSTEMUI";
public static final int COUNT_ONE_PAGE = 8;
public static final int COUNT_ONE_PAGE2 = 10;
public static final String YOUNGSYSTEM_APP_TONGBU = "com.school.app.syn"; // 小学系统 同步教材app
/**
*
*/
public static final String number[] = {
"1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "0", "11"};
public static final String STORE = "store";
public static final String CATEGORY_THREE = "3";
public static final String CATEGORY_SIX = "6";
public static final String CATEGORY_UPSIX = "10";
public static final String CLOSE_REST_WINDOW = "colse_rest_window";
public static final String STOP_LOOPING_TIMER = "stop_looping_timer";
public static final String START_LOOPING_TIMER = "start_looping_timer";
public static String DOWNLOADAPP_CALLBACK = "com.colorflykids.downloadapp"; // 子界面下载回调 提示更新UI
public static String MENU_YOUYOU = "youyou";
public static String MENU_LANGUAGE = "语言启蒙";
public static String MENU_HABIT = "行为习惯";
public static String MENU_KNOWLEDGE = "生活认知";
public static String MENU_SECURITY = "安全自理";
public static String MENU_PROMOTION = "入园-综合提升";
public static String MENU_LY = "优优乐园";
public static String MENU_YW = "语文知识";
public static String MENU_SX = "数理逻辑";
public static String MENU_YY = "英语启蒙";
public static String MENU_QS = "情商培养";
public static String MENU_YS = "艺术提升";
public static String MENU_ZH = "学前-综合提升";
public static String MENU_TONGBUJIAOCAI = "同步教材";
public static String MENU_YUWEN = "语文";
public static String MENU_SHUXUE = "数学";
public static String MENU_YINGYU = "英语";
public static String MENU_ZONGHETISHEGN = "小学-综合提升";
public static String[] babySystem = {MENU_LANGUAGE, MENU_HABIT, MENU_KNOWLEDGE, MENU_SECURITY, MENU_PROMOTION};
public static String[] childSystem = {MENU_LY, MENU_YW, MENU_SX, MENU_YY, MENU_QS, MENU_YS, MENU_ZH};
public static String[] youngSystem = {MENU_YUWEN, MENU_SHUXUE, MENU_YINGYU, MENU_ZONGHETISHEGN};
public static String[] sonSystem = {MENU_HABIT, MENU_SECURITY, MENU_LANGUAGE, MENU_KNOWLEDGE, MENU_PROMOTION,
MENU_LY, MENU_YW, MENU_SX, MENU_YY, MENU_QS, MENU_YS, MENU_ZH,
MENU_TONGBUJIAOCAI, MENU_YUWEN, MENU_SHUXUE, MENU_YINGYU, MENU_YINGYU, MENU_ZONGHETISHEGN};
public static String[][] tagList = {babySystem, childSystem, youngSystem};
public static String subcategories[][] = {babySystem, childSystem, youngSystem};
public static String system[] = {"入园系统", "学前系统", "小学系统"};
public static String systemandno[] = {"入园系统", "学前系统", "小学系统", "未分配"};
protected static Toast toast = null;
private static String oldMsg;
private static long oneTime = 0;
private static long twoTime = 0;
// 积分记录 达人标准次数记录
// MD5 设备地址标识
public static String getMAC(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // 如果当前设备系统大于等于6.0 使用下面的方法
return getMac();
} else {
try {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// 获取MAC地址
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String mac = wifiInfo.getMacAddress();
if (null == mac) {
// 未获取到
mac = "";
}
return mac;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
/**
* 获取手机的MAC地址
*
* @return
*/
public static String getMac() {
String str = "";
String macSerial = "";
try {
Process pp = Runtime.getRuntime().exec(
"cat /sys/class/net/wlan0/address");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (macSerial == null || "".equals(macSerial)) {
try {
return loadFileAsString("/sys/class/net/eth0/address")
.toUpperCase().substring(0, 17);
} catch (Exception e) {
e.printStackTrace();
macSerial = getAndroid7MAC();
}
}
return macSerial;
}
/**
* 兼容7.0获取不到的问题
*
* @return
*/
public static String getAndroid7MAC() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0"))
continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "";
}
public static String loadFileAsString(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
String text = loadReaderAsString(reader);
reader.close();
return text;
}
public static String loadReaderAsString(Reader reader) throws Exception {
StringBuilder builder = new StringBuilder();
char[] buffer = new char[4096];
int readLength = reader.read(buffer);
while (readLength >= 0) {
builder.append(buffer, 0, readLength);
readLength = reader.read(buffer);
}
return builder.toString();
}
// MD5 设备地址标识
public static String getMD5(Context context) {
String WLANMAC = getMAC(context);
// compute md5
MessageDigest m = null;
try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (WLANMAC != null && !WLANMAC.equals("")) {
m.update(WLANMAC.getBytes(), 0, WLANMAC.length());
} else if (getSimSerialNumber(context) != null && !getSimSerialNumber(context).equals("")) {
m.update(getSimSerialNumber(context).getBytes(), 0, getSimSerialNumber(context).length());
} else {
m.update(getPesudoUniqueID().getBytes(), 0, getPesudoUniqueID().length());
}
// get md5 bytes
byte p_md5Data[] = m.digest();
// create a hex string
String m_szUniqueID = new String();
for (int i = 0; i < p_md5Data.length; i++) {
int b = (0xFF & p_md5Data[i]);
// if it is a single digit, make sure it have 0 in front (proper padding)
if (b <= 0xF)
m_szUniqueID += "0";
// add number to string
m_szUniqueID += Integer.toHexString(b);
} // hex string to uppercase
m_szUniqueID = m_szUniqueID.toUpperCase();
return m_szUniqueID;
}
private static String getSimSerialNumber(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
@SuppressLint("MissingPermission") String simSerialNumber = tm.getSimSerialNumber();
return simSerialNumber;
}
private static String getPesudoUniqueID() {
String m_szDevIDShort = "35" + //we make this look like a valid IMEI
Build.BOARD.length() % 10 +
Build.BRAND.length() % 10 +
Build.CPU_ABI.length() % 10 +
Build.DEVICE.length() % 10 +
Build.DISPLAY.length() % 10 +
Build.HOST.length() % 10 +
Build.ID.length() % 10 +
Build.MANUFACTURER.length() % 10 +
Build.MODEL.length() % 10 +
Build.PRODUCT.length() % 10 +
Build.TAGS.length() % 10 +
Build.TYPE.length() % 10 +
Build.USER.length() % 10;
return m_szDevIDShort;
}
// 防止连续点击
private static long lastClickTime;
public static boolean isFastDoubleClick() {
long time = System.currentTimeMillis();
long timeD = time - lastClickTime;
if (0 < timeD && timeD < 500) {
return true;
}
lastClickTime = time;
return false;
}
// 5分钟 = 1 转换成时间
public static String getRangeTime(int range) {
StringBuffer sBuffer = new StringBuffer();
String hour;
String minute;
if ((range / 12) >= 10) {
hour = range / 12 + "";
} else {
hour = "0" + range / 12 + "";
}
if ((range % 12) > 0) {
minute = ":" + range % 12 / 2 + "0";
} else {
minute = ":00";
}
sBuffer.append(hour.trim());
sBuffer.append(minute.trim());
return sBuffer.toString();
}
// 根据日期取得星期几
public static String getWeek(Date date) {
String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (week_index < 0) {
week_index = 0;
}
return weeks[week_index];
}
// 非空判断
public static boolean isEmpty(String s) {
if (null == s)
return true;
if (s.length() == 0)
return true;
if (s.trim().length() == 0)
return true;
return false;
}
// 手动隐藏键盘
public static void CloseKeyBoard(Context context) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
System.out.println("isActive:" + imm.isActive());
if (imm.isActive()) {
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
// 接受软键盘输入
public static void hideKeyboard(Context context, View view) {
if (context == null || view == null) {
return;
}
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// 卸载app
public static void unInstallAPP(Context context, String packageName) {
if (!TextUtils.isEmpty(packageName) && !AppsManagerUtils.isSystemApp(context, packageName)) {
if (AppsManagerUtils.isSystemApp(context, packageName)) {
Toast.makeText(MyApplication.getAppContext(), "系统应用无法卸载!", Toast.LENGTH_SHORT).show();
} else {
Uri packageURI = Uri.parse("package:" + packageName);
Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
context.startActivity(intent);
}
} else {
Toast.makeText(MyApplication.getAppContext(), "系统应用无法卸载!", Toast.LENGTH_SHORT).show();
}
}
// 打开app
public static void startApp(Context context, String packageName,
String activityName) {
if (TextUtils.isEmpty(packageName))
return;
try {
Intent intent = null;
if (TextUtils.isEmpty(activityName)) {
intent = context.getPackageManager().getLaunchIntentForPackage(
packageName);
} else {
intent = new Intent();
intent.setComponent(new ComponentName(packageName, activityName));
}
if (intent == null) {
intent = getLaunchIntentForNoCategory(context, packageName);
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Intent getLaunchIntentForNoCategory(Context context,
String packageName) {
Intent intent = null;
PackageManager packageManager = context.getPackageManager();
PackageInfo packageinfo = null;
try {
packageinfo = packageManager.getPackageInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (packageinfo == null) {
return null;
}
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.setPackage(packageinfo.packageName);
List<ResolveInfo> resolveinfoList = packageManager
.queryIntentActivities(resolveIntent, 0);
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null) {
String className = resolveinfo.activityInfo.name;
intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
}
return intent;
}
// 设置系统亮度模式
public static void systemBrightness(Context context) {
try {
SharedPreferences mPrefs = context.getSharedPreferences("colorflykids", 0);
boolean initSetting = mPrefs.getBoolean("init_setting", true);
if (initSetting) {
mPrefs.edit().putBoolean("init_setting", false).commit();
}
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
mPrefs.edit().putBoolean("first_init", false).commit();
} catch (Exception err) {
err.printStackTrace();
}
}
// 更新 版本比较
public static boolean isUpdate(String oldVersion, String newVersion) {
if (TextUtils.isEmpty(oldVersion) || TextUtils.isEmpty(newVersion) || oldVersion.equals(newVersion)) {
return false;
}
String[] oldVersionSp = oldVersion.replaceAll("[^.\\d]", "").trim().split("\\.");
String[] newVsersionSp = newVersion.replaceAll("[^.\\d]", "").trim().split("\\.");
int index = 0;
int minLen = Math.min(oldVersionSp.length, newVsersionSp.length);
int diff = 0;
while (index < minLen && (diff = Integer.parseInt(newVsersionSp[index]) - Integer.parseInt(oldVersionSp[index])) == 0) {
index++;
}
if (diff == 0) {
for (int i = index; i < oldVersionSp.length; i++) {
if (Integer.parseInt(oldVersionSp[i]) > 0) {
return false;
}
}
for (int i = index; i < newVsersionSp.length; i++) {
if (Integer.parseInt(newVsersionSp[i]) > 0) {
return true;
}
}
} else {
return diff > 0 ? true : false;
}
return false;
}
/***
* 半角转换为全角
*
* @param input
* @return
*/
public static String ToDBC(String input) {
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == 12288) {
c[i] = (char) 32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char) (c[i] - 65248);
}
return new String(c);
}
public static void showToast(Context context, String s) {
if (toast == null) {
toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
toast.show();
oneTime = System.currentTimeMillis();
} else {
twoTime = System.currentTimeMillis();
if (s.equals(oldMsg)) {
if (twoTime - oneTime > Toast.LENGTH_SHORT) {
toast.show();
}
} else {
oldMsg = s;
toast.setText(s);
toast.show();
}
}
oneTime = twoTime;
}
public static boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] leftTop = {0, 0};
//获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
// 点击的是输入框区域保留点击EditText的事件
return false;
} else {
return true;
}
}
return false;
}
public static boolean isIntent(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
if (manager == null) {
return false;
}
// 检查网络连接,如果无网络可用,就不需要进行连网操作等
NetworkInfo networkinfo = manager.getActiveNetworkInfo();
if (networkinfo == null || !networkinfo.isAvailable()) {
return false;
}
return true;
}
public static String getTime(int time) {
int min = time / 60;
int sec = time % 60;
if (sec > 0) {
return String.valueOf(min + 1);
} else {
return String.valueOf(min);
}
}
public static String getTimeClick(int time) {
StringBuffer timeClick = new StringBuffer();
int min = time / 60;
int sec = time % 60;
timeClick.append(min >= 10 ? (int) Math.ceil(min / 10) : 0)
.append(min % 10)
.append(":")
.append(sec >= 10 ? (int) Math.ceil(sec / 10) : 0)
.append(sec % 10);
return timeClick.toString();
}
public static String getVersionName(Context context) {
// 获取packagemanager的实例
PackageManager packageManager = context.getPackageManager();
// getPackageName()是你当前类的包名0代表是获取版本信息
PackageInfo packInfo;
try {
packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
String version = packInfo.versionName.replaceAll("[a-zA-Z]", "").trim();
;
return version;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static float dp2px(Resources resources, float dp) {
final float scale = resources.getDisplayMetrics().density;
return dp * scale + 0.5f;
}
public static float sp2px(Resources resources, float sp) {
final float scale = resources.getDisplayMetrics().scaledDensity;
return sp * scale;
}
public static String getTime() {
long time = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = new Date(time);
String t1 = format.format(d1);
return t1;
}
private static void getAdmin(Context context, ComponentName componentName) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "宏云萌书院OS");
context.startActivity(intent);
}
/**
* 获取设备序列号
*
* @return
*/
public static String getSerial() {
return Build.SERIAL;
// return "QNS3AI000111";
// return "QNW8WJ900002";
}
public static final long A_GB = 1073741824;
public static final long A_MB = 1048576;
public static final int A_KB = 1024;
public static String fmtSpace(long space) {
if (space <= 0) {
return "0";
}
double gbValue = (double) space / A_GB;
if (gbValue >= 1) {
return String.format("%.2fGB", gbValue);
} else {
double mbValue = (double) space / A_MB;
// Log.e("GB", "gbvalue=" + mbValue);
if (mbValue >= 1) {
return String.format("%.2fMB", mbValue);
} else {
final double kbValue = space / A_KB;
return String.format("%.2fKB", kbValue);
}
}
}
public static String transferLongToDate(Long millSec) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(millSec);
return sdf.format(date);
}
public static String getSn() {
return Build.SERIAL;
}
public static Bitmap createQRImage(String content, int widthPix, int heightPix) {
try {
// if (content == null || "".equals(content)) {
// return false;
// }
//配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
hints.put(EncodeHintType.MARGIN, 1); //default is 4
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = null;
try {
bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
} catch (WriterException e) {
e.printStackTrace();
}
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
//
// if (logoBm != null) {
// bitmap = addLogo(bitmap, logoBm);
// }
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的
// 内存消耗巨大!
return bitmap;
// return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//判断是否为系统应用
public static boolean isSystemApp(Context context, String pkgName) {
boolean isSystemApp = false;
PackageInfo pi = null;
try {
PackageManager pm = context.getPackageManager();
pi = pm.getPackageInfo(pkgName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
Log.e("isSystemApp", e.getMessage(), e);
}
// 是系统中已安装的应用
if (pi != null) {
boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
isSystemApp = isSysApp || isSysUpd;
}
return isSystemApp;
}
public static Bitmap getRoundedBitmap(Bitmap mBitmap, Context context) {
Bitmap bgBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Bitmap mask = BitmapFactory.decodeResource(context.getResources(), R.drawable.mask);
int width = mask.getWidth();
int height = mask.getHeight();
Bitmap bitmapScale = Bitmap.createScaledBitmap(mBitmap, width, height, true);
// Palette p = Palette.from(mBitmap).generate();
// Palette.Swatch vibrant = p.getVibrantSwatch();//有活力的
// int color = vibrant.getRgb(); //样本中的像素数量
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas();
Paint paint = new Paint();
canvas.setBitmap(result);
// canvas.drawColor(color);
canvas.drawBitmap(mask, 0, 0, paint);
// paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmapScale, 0, 0, paint);
// return result;
Bitmap result2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas2 = new Canvas();
Paint paint2 = new Paint();
canvas2.setBitmap(result2);
canvas2.drawBitmap(mask, 0, 0, paint2);
paint2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas2.drawBitmap(result, 0, 0, paint2);
return result2;
// Canvas mCanvas = new Canvas();
// mCanvas.setBitmap(bgBitmap);
// Paint mPaint = new Paint();
// RectF mRectM = new RectF(scaleM, scaleM, mBitmap.getWidth() - scaleM, mBitmap.getHeight() - scaleM); //设置剪裁圆角的区域
// Rect mRect = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
// RectF mRectF = mRectM;
//
// float roundPx = 15; //圆角半径
// mPaint.setAntiAlias(true);
// //Log.d("wy"+TAG,"mBitmap.getWidth()="+mBitmap.getWidth()+", mBitmap.getHeight()="+mBitmap.getHeight());
// mCanvas.drawRoundRect(mRectF, roundPx, roundPx, mPaint);
// mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// mCanvas.drawBitmap(mBitmap, mRect, mRect, mPaint);
// return bgBitmap;
}
}