package com.anthony.library.utils;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.io.File;
import java.util.List;
/**
* Created by Anthony on 2016/1/25.
* Class Note:
*
*/
public class AppUtils {
/**
* whether this process is named with processName
*
* @param context
* @param processName
* @return <ul>
* return whether this process is named with processName
* <li>if context is null, return false</li>
* <li>if {@link ActivityManager#getRunningAppProcesses()} is null, return false</li>
* <li>if one process of {@link ActivityManager#getRunningAppProcesses()} is equal to processName, return
* true, otherwise return false</li>
* </ul>
*/
public static boolean isNamedProcess(Context context, String processName) {
if (context == null) {
return false;
}
int pid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> processInfoList = manager.getRunningAppProcesses();
if (ListUtils.isEmpty(processInfoList)) {
return false;
}
for (RunningAppProcessInfo processInfo : processInfoList) {
if (processInfo != null && processInfo.pid == pid
&& ObjectUtils.isEquals(processName, processInfo.processName)) {
return true;
}
}
return false;
}
/**
* whether application is in background
* <ul>
* <li>need use permission android.permission.GET_TASKS in Manifest.xml</li>
* </ul>
*
* @param context
* @return if application is in background return true, otherwise return false
*/
public static boolean isApplicationInBackground(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskList = am.getRunningTasks(1);
if (taskList != null && !taskList.isEmpty()) {
ComponentName topActivity = taskList.get(0).topActivity;
if (topActivity != null && !topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
/**
* get the package information of the context
*
* @param context
* @return
*/
public static PackageInfo getPackageInfo(Context context) {
PackageInfo info = null;
try {
info = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace(System.err);
}
if (info == null)
info = new PackageInfo();
return info;
}
/**
* whether the external storage (SDCard) exists
*
* @return
*/
public static boolean isStorageExists() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
/**
* whether the network is connected
*
* @param context
* @return
*/
public static boolean isNetworkConnected(Context context) {
if (null == context) {
return false;
}
// 获取手机所有连接管理对象(包括wifi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
// 获取网络连接管理的对象
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 判断当前网络是否已经连接
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
/**
* 没有网络
*/
public static final int NETWORKTYPE_INVALID = 0;
/**
* wap网络
*/
public static final int NETWORKTYPE_WAP = 1;
/**
* 2G网络
*/
public static final int NETWORKTYPE_2G = 2;
/**
* 3G和3G以上网络,或统称为快速网络
*/
public static final int NETWORKTYPE_3G = 3;
/**
* wifi网络
*/
public static final int NETWORKTYPE_WIFI = 4;
/**
* get the network type (wifi,wap,2g,3g)
*
* @param context
* @return
*/
public static int getNetWorkType(Context context) {
int mNetWorkType = NETWORKTYPE_INVALID;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String type = networkInfo.getTypeName();
if (type.equalsIgnoreCase("WIFI")) {
mNetWorkType = NETWORKTYPE_WIFI;
} else if (type.equalsIgnoreCase("MOBILE")) {
String proxyHost = android.net.Proxy.getDefaultHost();
mNetWorkType = TextUtils.isEmpty(proxyHost)
? (isFastMobileNetwork(context) ? NETWORKTYPE_3G : NETWORKTYPE_2G)
: NETWORKTYPE_WAP;
}
} else {
mNetWorkType = NETWORKTYPE_INVALID;
}
return mNetWorkType;
}
private static boolean isFastMobileNetwork(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
switch (telephonyManager.getNetworkType()) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
case TelephonyManager.NETWORK_TYPE_EHRPD:
return true; // ~ 1-2 Mbps
case TelephonyManager.NETWORK_TYPE_EVDO_B:
return true; // ~ 5 Mbps
case TelephonyManager.NETWORK_TYPE_HSPAP:
return true; // ~ 10-20 Mbps
case TelephonyManager.NETWORK_TYPE_IDEN:
return false; // ~25 kbps
case TelephonyManager.NETWORK_TYPE_LTE:
return true; // ~ 10+ Mbps
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
return false;
default:
return false;
}
}
/**
* show dialog to choose whether go to the view of network setting
*
* @param context
*/
public static void setNetworkMethod(final Context context) {
// 提示对话框
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
try {
builder.setTitle("网络设置提示")
.setMessage("网络连接不可用,是否进行设置?")
.setPositiveButton("设置",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Intent intent = null;
// 判断手机系统的版本 即API大于10 就是3.0或以上版本
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).show();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* install APK File from folder
* @param context
* @param apkFullFileName apk path+apk name
*/
public static void installApk(Context context,String apkFullFileName) {
// String saveFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/Download/" + downloadFileName;
File apkFile = new File(apkFullFileName);
if (!apkFile.exists()) {
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
//分享
public static void share(Context context, String questionTitle, String questionUrl) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//noinspection deprecation
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
share.putExtra(Intent.EXTRA_TEXT, questionTitle + " " + questionUrl + " 分享自Anthony Github");
context.startActivity(Intent.createChooser(share,"分享至。。。"));
}
/**
* 安装文件
*
* @param data
*/
public static void promptInstall(Context context, Uri data) {
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(data, "application/vnd.android.package-archive");
// FLAG_ACTIVITY_NEW_TASK 可以保证安装成功时可以正常打开 app
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(promptInstall);
}
public static void copy2clipboard(Context context, String text) {
ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("clip", text);
cm.setPrimaryClip(clip);
}
/**
* 显示软键盘
*/
public static void openSoftInput(EditText et) {
InputMethodManager inputMethodManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(et, InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 隐藏软键盘
*/
public static void hideSoftInput(EditText et) {
InputMethodManager inputMethodManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(et.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 获取SD卡路径
*
* @return 如果sd卡不存在则返回null
*/
public static File getSDPath() {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //判断sd卡是否存在
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory();//获取跟目录
}
return sdDir;
}
/**
* 获取版本名称
*/
public static String getAppVersionName(Context context) {
String versionName = "";
try {
// ---get the package info---
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
versionName = pi.versionName;
if (versionName == null || versionName.length() <= 0) {
return "";
}
} catch (Exception e) {
Log.e("VersionInfo", "Exception", e);
}
return versionName;
}
/**
* 获取版本号
*/
public static int getAppVersionCode(Context context) {
int versioncode = -1;
try {
// ---get the package info---
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
versioncode = pi.versionCode;
} catch (Exception e) {
Log.e("VersionInfo", "Exception", e);
}
return versioncode;
}
public static String getIMEI(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDeviceId();
}
public static boolean isServiceRunning(Context context, Class serviceClass) {
ActivityManager manager =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public static void toggleComponent(Context context, Class componentClass, boolean enable) {
ComponentName componentName = new ComponentName(context, componentClass);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(componentName,
enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}