记录那些经常用却又打死记不住的代码(一)

Posted by alonealice on 2017-07-20

在开发过程中,总会遇到很多其实经常写,但又死活记不住(也许是本人比较笨),每次都需要google的一些代码。这篇文章就是记录那些代码,以方便以后快速找到。

跳转到系统图库页面

1
2
3
Intent albumIntent = new Intent(Intent.ACTION_PICK);
albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
activity.startActivityForResult(albumIntent, 0);

跳转到系统相机页面

1
2
3
Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileName)));
activity.startActivityForResult(getImageByCamera, 0);

判断程序是否在后台

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ActivityManager activityManager = (ActivityManager) context.getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
String packageName = context.getApplicationContext().getPackageName();
/**
* 获取Android设备中所有正在运行的App
*/
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;

发送/取消闹钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Intent intent = new Intent(context, AlarmClockBroadcast.class);
// FLAG_UPDATE_CURRENT:如果PendingIntent已经存在,保留它并且只替换它的extra数据。
// FLAG_CANCEL_CURRENT:如果PendingIntent已经存在,那么当前的PendingIntent会取消掉,然后产生一个新的PendingIntent。
PendingIntent pi = PendingIntent.getBroadcast(context,
id, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);

// 设置闹钟,当前版本为19(4.4)或以上使用精准闹钟
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextTime, pi);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, nextTime, pi);
}

//取消闹钟
am.cancel(pi);

屏幕宽度高度

1
2
3
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int width=dm.widthPixels;
int height=dm.heightPixels;

Android获取StatusBar高度

1
2
3
4
5
6
int x = 0, statusBarHeight = 0;
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);

获取设备的imsi

1
2
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String imsi = mTelephonyMgr.getSubscriberId();

获取设备的imei

1
2
TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String imei = mTelephonyMgr.getDeviceId();

获取应用版本和版本号

1
2
String appVersion=context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
int appVersionCode=context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;

获取屏幕亮度

1
2
3
ContentResolver resolver = activity.getContentResolver();
int nowBrightnessValue = android.provider.Settings.System.getInt(
resolver, Settings.System.SCREEN_BRIGHTNESS);

dp转px

1
2
3
DisplayMetrics dm = context.getResources().getDisplayMetrics();
float density=dm.density;
int px= (int) (dp * density + 0.5f);

px转dp

1
2
3
DisplayMetrics dm = context.getResources().getDisplayMetrics();
float density=dm.density;
int dp= (int) (px / density + 0.5f);

sp转px

1
2
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
int px=(int) (spValue * fontScale + 0.5f);

px转sp

1
2
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
int sp=(int) (pxValue / fontScale + 0.5f);

获取缓存文件

1
File f =context.getExternalCacheDir();

获取SD卡路径

1
File f =context.getExternalCacheDir();

获取根目录文件

1
2
3
4
File f = context.getExternalFilesDir("");
if(null==f){
f = context.getFilesDir();
}

写文件

1
2
3
4
5
File file = new File(fileName);  
FileOutputStream fos = new FileOutputStream(file);
byte [] bytes = write.getBytes();
fos.write(bytes);
fos.close();

读文件

1
2
3
4
5
FileInputStream fin = new FileInputStream(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
fin.close();

读取assets或资源文件

1
2
3
4
5
6
7
8
9
10
11
12
//InputStream is = activity.getResources().openRawResource(id)
InputStream is = activity.getAssets().open(filePath);
InputStreamReader inputStreamReader;
inputStreamReader = new InputStreamReader(is, "utf-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer("");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
return sb.toString();

Bitmap保存文件

1
2
3
4
FileOutputStream fos = new FileOutputStream(file, false);
bitmap.compress(Bitmap.CompressFormat.JPEG,100, fos);
fos.flush();
fos.close();

Bitmap.Option的设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//是否只解析边界(true,则解析返回null,但是option有outHeight和outWidth)
BitmapFactory.decodeFile(res, options);
options.inPreferredConfig= Bitmap.Config.ARGB_8888;//图片解码时使用的颜色模式(默认8888)
options.inSampleSize =2;//缩放倍数(整数)
options.inJustDecodeBounds = false;
options.inBitmap=bitmap;//是否重用该bitmap
options.inPremultiplied=true;//如果设置了true(默认是true),那么返回的图片RGB都会预乘透明通道A后的颜色,
// 系统View或者Canvas绘制图片,不建议设置为fase,否则会抛出异常,
// 这是因为系统会假定所有图像都预乘A通道的已简化绘制时间.
// 设置inPremultiplied的同时,设置inScale会导致绘制的颜色不正确.
options.inDither=true; // 设置是否抖动处理图片(android N 被废弃)
options.inMutable=true; // 是否是mutable可变的(BitmapFactory.decodeResource是可变的,BitmapFactory.decodeFile是不可变的)
options.inScaled=true; //是否缩放
options.inDensity=400; //设置位图的像素密度,即每英寸有多少个像素
options.inTargetDensity=400; //设置绘制位图的屏幕密度,与inScale和inDesity一起使用,来对位图进行放缩.
options.inScreenDensity=400; //表示正在使用的实际屏幕的像素密度.

Bitmap旋转角度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
ExifInterface exif = null;
int degree = 0;
try {
exif = new ExifInterface(imgPath);
} catch (IOException e) {
e.printStackTrace();
exif = null;
}
if (exif != null) {
int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
switch (ori) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
default:
degree = 0;
break;
}
}

MD5加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
try {
byte[] btInput = s.getBytes();
// get MessageDigest Object
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
// get Ciphertext
byte[] md = mdInst.digest();
// Ciphertext to byte
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return "0";
}

监听锁屏开屏

1
2
3
4
5
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);//屏幕打开
filter.addAction(Intent.ACTION_SCREEN_OFF);//屏幕关闭
filter.addAction(Intent.ACTION_USER_PRESENT);//解锁
context.registerReceiver(receiver, filter);

直接判断屏幕是否关闭

1
2
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isInteractive();

设置StatusBar颜色

1
2
3
4
5
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(activity,colorId));
}

设置StatusBar透明

1
2
3
4
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
((ViewGroup)activity.getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0).setPadding(0, DeviceUtil.getStatusBarHeight(activity), 0, 0);
}

设置MIUI状态栏主题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
boolean result = false;
if (window != null) {
Class clazz = window.getClass();
try {
int darkModeFlag = 0;
Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
if(dark){
extraFlagField.invoke(window,darkModeFlag,darkModeFlag);//状态栏透明且黑色字体
}else{
extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
}
result=true;
}catch (Exception e){

}
}
return result;

设置Flyme状态栏主题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
boolean result = false;
if (window != null) {
try {
WindowManager.LayoutParams lp = window.getAttributes();
Field darkFlag = WindowManager.LayoutParams.class
.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class
.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(lp);
if (dark) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(lp, value);
window.setAttributes(lp);
result = true;
} catch (Exception e) {

}
}
return result;

时间Long类型转固定格式

1
2
SimpleDateFormat simpleDateFormat=new SimpleDateFormat(style, Locale.getDefault());
return simpleDateFormat.format(new Date(time));