Android代码片段

1.拨打电话

1

2

3

public static void call(Context context, String phoneNumber) {

context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)));

}

2.跳转至拨号界面

1

2

3

public static void callDial(Context context, String phoneNumber) {

context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));

}

3.发送短信

1

2

3

4

5

6

7

8

public static void sendSms(Context context, String phoneNumber,

String content) {

Uri uri = Uri.parse("smsto:"

+ (TextUtils.isEmpty(phoneNumber) ? "" : phoneNumber));

Intent intent = new Intent(Intent.ACTION_SENDTO, uri);

intent.putExtra("sms_body", TextUtils.isEmpty(content) ? "" : content);

context.startActivity(intent);

}

4.唤醒屏幕并解锁

1

2

3

4

5

6

7

8

9

10

11

12

13

14

public static void wakeUpAndUnlock(Context context){

KeyguardManager km= (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");

//解锁

kl.disableKeyguard();

//获取电源管理器对象

PowerManager pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE);

//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag

PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");

//点亮屏幕

wl.acquire();

//释放

wl.release();

}

5.需要添加权限

1

2

<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

6.判断当前App处于前台还是后台状态

1

2

3

4

5

6

7

8

9

10

11

12

13

public static boolean isApplicationBackground(final Context context) {

ActivityManager am = (ActivityManager) context

.getSystemService(Context.ACTIVITY_SERVICE);

@SuppressWarnings("deprecation")

List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);

if (!tasks.isEmpty()) {

ComponentName topActivity = tasks.get(0).topActivity;

if (!topActivity.getPackageName().equals(context.getPackageName())) {

return true;

}

}

return false;

}

7.需要添加权限

1

2

<uses-permission

android:name="android.permission.GET_TASKS" />

8.判断当前手机是否处于锁屏(睡眠)状态

1

2

3

4

5

6

public static boolean isSleeping(Context context) {

KeyguardManager kgMgr = (KeyguardManager) context

.getSystemService(Context.KEYGUARD_SERVICE);

boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();

return isSleeping;

}

9.判断当前是否有网络连接

1

2

3

4

5

6

7

8

9

public static boolean isOnline(Context context) {

ConnectivityManager manager = (ConnectivityManager) context

.getSystemService(Activity.CONNECTIVITY_SERVICE);

NetworkInfo info = manager.getActiveNetworkInfo();

if (info != null && info.isConnected()) {

return true;

}

return false;

}

10.判断当前是否是WIFI连接状态

1

2

3

4

5

6

7

8

9

10

public static boolean isWifiConnected(Context context) {

ConnectivityManager connectivityManager = (ConnectivityManager) context

.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo wifiNetworkInfo = connectivityManager

.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (wifiNetworkInfo.isConnected()) {

return true;

}

return false;

}

11.安装APK

1

2

3

4

5

6

7

8

9

10

public static void installApk(Context context, File file) {

Intent intent = new Intent();

intent.setAction("android.intent.action.VIEW");

intent.addCategory("android.intent.category.DEFAULT");

intent.setType("application/vnd.android.package-archive");

intent.setDataAndType(Uri.fromFile(file),

"application/vnd.android.package-archive");

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(intent);

}

12.判断当前设备是否为手机

1

2

3

4

5

6

7

8

9

public static boolean isPhone(Context context) {

TelephonyManager telephony = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {

return false;

} else {

return true;

}

}

13.获取当前设备宽高,单位px

1

2

3

4

5

6

7

8

9

10

11

12

13

@SuppressWarnings("deprecation")

public static int getDeviceWidth(Context context) {

WindowManager manager = (WindowManager) context

.getSystemService(Context.WINDOW_SERVICE);

return manager.getDefaultDisplay().getWidth();

}

@SuppressWarnings("deprecation")

public static int getDeviceHeight(Context context) {

WindowManager manager = (WindowManager) context

.getSystemService(Context.WINDOW_SERVICE);

return manager.getDefaultDisplay().getHeight();

}

14.获取当前设备的IMEI,需要与上面的isPhone()一起使用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@TargetApi(Build.VERSION_CODES.CUPCAKE)

public static String getDeviceIMEI(Context context) {

String deviceId;

if (isPhone(context)) {

TelephonyManager telephony = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

deviceId = telephony.getDeviceId();

} else {

deviceId = Settings.Secure.getString(context.getContentResolver(),

Settings.Secure.ANDROID_ID);

}

return deviceId;

}

15.获取当前设备的MAC地址

1

2

3

4

5

6

7

8

9

10

11

12

public static String getMacAddress(Context context) {

String macAddress;

WifiManager wifi = (WifiManager) context

.getSystemService(Context.WIFI_SERVICE);

WifiInfo info = wifi.getConnectionInfo();

macAddress = info.getMacAddress();

if (null == macAddress) {

return "";

}

macAddress = macAddress.replace(":", "");

return macAddress;

}

16.获取当前程序的版本号

1

2

3

4

5

6

7

8

9

10

public static String getAppVersion(Context context) {

String version = "0";

try {

version = context.getPackageManager().getPackageInfo(

context.getPackageName(), 0).versionName;

} catch (PackageManager.NameNotFoundException e) {

e.printStackTrace();

}

return version;

}

17.收集设备信息,用于信息统计分析

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

26

27

28

29

30

31

32

33

34

35

36

37

38

39

public static Properties collectDeviceInfo(Context context) {

Properties mDeviceCrashInfo = new Properties();

try {

PackageManager pm = context.getPackageManager();

PackageInfo pi = pm.getPackageInfo(context.getPackageName(),

PackageManager.GET_ACTIVITIES);

if (pi != null) {

mDeviceCrashInfo.put(VERSION_NAME,

pi.versionName == null ? "not set" : pi.versionName);

mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);

}

} catch (PackageManager.NameNotFoundException e) {

Log.e(TAG, "Error while collect package info", e);

}

Field[] fields = Build.class.getDeclaredFields();

for (Field field : fields) {

try {

field.setAccessible(true);

mDeviceCrashInfo.put(field.getName(), field.get(null));

} catch (Exception e) {

Log.e(TAG, "Error while collect crash info", e);

}

}

return mDeviceCrashInfo;

}

public static String collectDeviceInfoStr(Context context) {

Properties prop = collectDeviceInfo(context);

Set deviceInfos = prop.keySet();

StringBuilder deviceInfoStr = new StringBuilder("{\n");

for (Iterator iter = deviceInfos.iterator(); iter.hasNext();) {

Object item = iter.next();

deviceInfoStr.append("\t\t\t" + item + ":" + prop.get(item)

+ ", \n");

}

deviceInfoStr.append("}");

return deviceInfoStr.toString();

}

18.是否有SD卡

1

2

3

4

public static boolean haveSDCard() {

return android.os.Environment.getExternalStorageState().equals(

android.os.Environment.MEDIA_MOUNTED);

}

19.动态隐藏软键盘

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@TargetApi(Build.VERSION_CODES.CUPCAKE)

public static void hideSoftInput(Activity activity) {

View view = activity.getWindow().peekDecorView();

if (view != null) {

InputMethodManager inputmanger = (InputMethodManager) activity

.getSystemService(Context.INPUT_METHOD_SERVICE);

inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);

}

}

@TargetApi(Build.VERSION_CODES.CUPCAKE)

public static void hideSoftInput(Context context, EditText edit) {

edit.clearFocus();

InputMethodManager inputmanger = (InputMethodManager) context

.getSystemService(Context.INPUT_METHOD_SERVICE);

inputmanger.hideSoftInputFromWindow(edit.getWindowToken(), 0);

}

20.动态显示软键盘

1

2

3

4

5

6

7

8

9

@TargetApi(Build.VERSION_CODES.CUPCAKE)

public static void showSoftInput(Context context, EditText edit) {

edit.setFocusable(true);

edit.setFocusableInTouchMode(true);

edit.requestFocus();

InputMethodManager inputManager = (InputMethodManager) context

.getSystemService(Context.INPUT_METHOD_SERVICE);

inputManager.showSoftInput(edit, 0);

}

21.动态显示或者是隐藏软键盘

1

2

3

4

5

6

7

8

9

@TargetApi(Build.VERSION_CODES.CUPCAKE)

public static void toggleSoftInput(Context context, EditText edit) {

edit.setFocusable(true);

edit.setFocusableInTouchMode(true);

edit.requestFocus();

InputMethodManager inputManager = (InputMethodManager) context

.getSystemService(Context.INPUT_METHOD_SERVICE);

inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

}

22.主动回到Home,后台运行

1

2

3

4

5

6

7

public static void goHome(Context context) {

Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);

mHomeIntent.addCategory(Intent.CATEGORY_HOME);

mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK

| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

context.startActivity(mHomeIntent);

}

23.获取状态栏高度
注意,要在onWindowFocusChanged中调用,在onCreate中获取高度为0

1

2

3

4

5

6

@TargetApi(Build.VERSION_CODES.CUPCAKE)

public static int getStatusBarHeight(Activity activity) {

Rect frame = new Rect();

activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

return frame.top;

}

24.获取状态栏高度+标题栏(ActionBar)高度
(注意,如果没有ActionBar,那么获取的高度将和上面的是一样的,只有状态栏的高度)

1

2

3

4

public static int getTopBarHeight(Activity activity) {

return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT)

.getTop();

}

25.获取MCC+MNC代码 (SIM卡运营商国家代码和运营商网络代码)
仅当用户已在网络注册时有效, CDMA 可能会无效(中国移动:46000 46002, 中国联通:46001,中国电信:46003)

1

2

3

4

5

public static String getNetworkOperator(Context context) {

TelephonyManager telephonyManager = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

return telephonyManager.getNetworkOperator();

}

26.返回移动网络运营商的名字
(例:中国联通、中国移动、中国电信) 仅当用户已在网络注册时有效, CDMA 可能会无效)

1

2

3

4

5

public static String getNetworkOperatorName(Context context) {

TelephonyManager telephonyManager = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

return telephonyManager.getNetworkOperatorName();

}

27.返回移动终端类型
PHONE_TYPE_NONE :0 手机制式未知
PHONE_TYPE_GSM :1 手机制式为GSM,移动和联通
PHONE_TYPE_CDMA :2 手机制式为CDMA,电信
PHONE_TYPE_SIP:3

1

2

3

4

5

public static int getPhoneType(Context context) {

TelephonyManager telephonyManager = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

return telephonyManager.getPhoneType();

}

28.判断手机连接的网络类型(2G,3G,4G)
联通的3G为UMTS或HSDPA,移动和联通的2G为GPRS或EGDE,电信的2G为CDMA,电信的3G为EVDO

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

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

public class Constants {

/**

* Unknown network class

*/

public static final int NETWORK_CLASS_UNKNOWN = 0;

/**

* wifi net work

*/

public static final int NETWORK_WIFI = 1;

/**

* "2G" networks

*/

public static final int NETWORK_CLASS_2_G = 2;

/**

* "3G" networks

*/

public static final int NETWORK_CLASS_3_G = 3;

/**

* "4G" networks

*/

public static final int NETWORK_CLASS_4_G = 4;

}

public static int getNetWorkClass(Context context) {

TelephonyManager telephonyManager = (TelephonyManager) context

.getSystemService(Context.TELEPHONY_SERVICE);

switch (telephonyManager.getNetworkType()) {

case TelephonyManager.NETWORK_TYPE_GPRS:

case TelephonyManager.NETWORK_TYPE_EDGE:

case TelephonyManager.NETWORK_TYPE_CDMA:

case TelephonyManager.NETWORK_TYPE_1xRTT:

case TelephonyManager.NETWORK_TYPE_IDEN:

return Constants.NETWORK_CLASS_2_G;

case TelephonyManager.NETWORK_TYPE_UMTS:

case TelephonyManager.NETWORK_TYPE_EVDO_0:

case TelephonyManager.NETWORK_TYPE_EVDO_A:

case TelephonyManager.NETWORK_TYPE_HSDPA:

case TelephonyManager.NETWORK_TYPE_HSUPA:

case TelephonyManager.NETWORK_TYPE_HSPA:

case TelephonyManager.NETWORK_TYPE_EVDO_B:

case TelephonyManager.NETWORK_TYPE_EHRPD:

case TelephonyManager.NETWORK_TYPE_HSPAP:

return Constants.NETWORK_CLASS_3_G;

case TelephonyManager.NETWORK_TYPE_LTE:

return Constants.NETWORK_CLASS_4_G;

default:

return Constants.NETWORK_CLASS_UNKNOWN;

}

}

29.判断当前手机的网络类型(WIFI还是2,3,4G)
需要用到上面的方法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public static int getNetWorkStatus(Context context) {

int netWorkType = Constants.NETWORK_CLASS_UNKNOWN;

ConnectivityManager connectivityManager = (ConnectivityManager) context

.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()) {

int type = networkInfo.getType();

if (type == ConnectivityManager.TYPE_WIFI) {

netWorkType = Constants.NETWORK_WIFI;

} else if (type == ConnectivityManager.TYPE_MOBILE) {

netWorkType = getNetWorkClass(context);

}

}

return netWorkType;

}

时间: 2024-12-29 23:24:58

Android代码片段的相关文章

Android - 代码片段

转载说明 本篇文章可能已经更新,最新文章请转:http://www.sollyu.com/android-code-snippets/ 说明 此篇文章为个人日常使用所整理的一此代码片段,此篇文正将会不定时更新 代码 评价应用 activity.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=" + activity.getPackageName()))); 获得系统分享列表 /** *

实用的Android代码片段集合(精)

1.        精确获取屏幕尺寸(例如:3.5.4.0.5.0寸屏幕) public static double getScreenPhysicalSize(Activity ctx) { DisplayMetrics dm = new DisplayMetrics(); ctx.getWindowManager().getDefaultDisplay().getMetrics(dm); double diagonalPixels = Math.sqrt(Math.pow(dm.widthP

【Android代码片段之八】监听Android屏幕是否锁屏

实现方法:1)通过BroadcastReceiver接收广播Intent.ACTION_SCREEN_ON和Intent.ACTION_SCREEN_OFF可以判断屏幕状态是否锁屏,但是只有屏幕状态发生改变时才会发出广播: 2)如果要在屏幕状态发生改变之前就想获取屏幕状态,可以通过反射机制调用PowerManager的isScreenOn方法 . 具体实现,见代码: 实现Screen状态监听的类ScreenObserver,实现如下: [java] view plaincopy package 

Android课程---Android Studio使用小技巧:提取方法代码片段

这篇文章主要介绍了Android Studio使用小技巧:提取方法代码片段,本文分享了一个快速复制粘贴方法代码片段的小技巧,并用GIF图演示,需要的朋友可以参考下 今天来给大家介绍一个非常有用的Studio Tips,有些时候我们在一个方法内部写了过多的代码,然后想要把一些代码提取出来再放在一个单独的方法里,通常我们的做法是复制粘贴,现在我来教给大家一个非常简洁的方法,先看下gif演示吧:

Android官方入门文档[16]创建一个Fragment代码片段

Android官方入门文档[16]创建一个Fragment代码片段 Creating a Fragment创建一个Fragment代码片段 This lesson teaches you to1.Create a Fragment Class2.Add a Fragment to an Activity using XML You should also read?Fragments 这节课教你1.创建一个Fragment代码片段类2.使用XML来添加一个Fragment代码片段给一个活动 你也

android有用代码片段(一)

有时候,需要一些小的功能,找到以后,就把它贴到了博客下面,作为留言,查找起来很不方便,所以就整理一下,方便自己和他人. 一.  获取系统版本号: PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0); int versionCode=nfo.versionCode string versionName=info.versionNam 二.获取系统信息: <span style=&quo

android 实用代码片段整理

android 常用代码片段,前1-10条是从网上摘录,向原作者致谢.后面为自己整理. 1.设置窗口格式为半透明 getWindow().setFormat(PixelFormat.TRANSLUCENT); 2.Android中在非UI线程里更新View的不同方法: * Activity.runOnUiThread( Runnable ) * View.post( Runnable ) * View.postDelayed( Runnable, long ) * Hanlder 3.全屏显示窗

[转]Android适配器之ArrayAdapter、SimpleAdapter和BaseAdapter的简单用法与有用代码片段

收藏ArrayAdapter.SimpleAdapter和BaseAdapter的一些简短代码片段,希望用时方便想起其用法. 1.ArrayAdapter 只可以简单的显示一行文本 代码片段: [java] view plaincopy ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, R.layout.item,//只能有一个定义了id的TextView data);//data既可以是数组,也可以是Li

Android适配器之ArrayAdapter、SimpleAdapter和BaseAdapter的简单用法与有用代码片段(转)

摘自:http://blog.csdn.net/shakespeare001/article/details/7926783 收藏ArrayAdapter.SimpleAdapter和BaseAdapter的一些简短代码片段,希望用时方便想起其用法. 1.ArrayAdapter 只可以简单的显示一行文本 代码片段: [java] view plaincopy ArrayAdapter<String> adapter = new ArrayAdapter<String>( this