持续更新中。。。
1、像素(PX)和 DP互转
public static int px2dip(Context context, float pxValue) {
final float density = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / density + 0.5f);
}
public static int dip2px(Context context, float dpValue) {
final float density = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * density + 0.5f);
}
2、检查网络是否可用
/**
* 获取网络状态
* @param context 上下文
* @return true 网络可用,false 网络不可用
*/
public static boolean getNetworkState(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null){
return info.isConnected();
}
return false;
}
3、创建桌面快捷方式
代码实现
/**创建桌面快捷方式*/
public void createShortcut(){
Intent it = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
//设置不允许重复添加
it.putExtra("duplicate", false);
//Log.e(TAG, "createShortcut()");
//设置生成桌面快捷方式名称
it.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
//设置生成桌面图片
//it.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.app_icon);
it.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
//设置图标启动Activity
it.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent("xxx.xx.xx.action.Main"));
//发送广播
sendBroadcast(it);
Utils.showToast(this, getString(R.string.create_short_success));
};
申明权限
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
然后在点击图标要启动的Activity下配置如下IntentFilter
<intent-filter>
<action android:name="xx.xxx.xx.action.Main" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
4、获取网络类型
/**
* 获取网络类型
* @param context 上下文
* @return 0 移动网络,1 WIFI网络, 7 Bluetooth等等
*/
public static int getNetworkType(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null){
return info.getType();
}
return -1;
}
5、获取程序版本
/**
* 获取当前版本信息
* @param context 上下文
* @throws NameNotFoundException
*/
public static String getLocalAppVersion(Context context) throws NameNotFoundException {
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
return info.versionName;
}