- package cn.sandy.demo.util;
- import java.io.DataOutputStream;
- import java.io.OutputStream;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import android.app.Activity;
- import android.content.Context;
- import android.os.Handler;
- import android.view.Gravity;
- import android.view.View;
- import android.widget.Toast;
- /**
- * 定义公共方法以及公共常量类,提供基础的数据及方法支持。
- *
- * @author sandy
- *
- */
- public class Commons {
- private static Toast bootom, center;
- /**
- * 应用于Activity的获取控件实例
- *
- * @param activity
- * @param id
- * @return
- */
- @SuppressWarnings("unchecked")
- public static <T extends View> T $(Activity activity, int id) {
- return (T) activity.findViewById(id);
- }
- /**
- * 应用于View的获取控件实例
- *
- * @param view
- * @param id
- * @return
- */
- @SuppressWarnings("unchecked")
- public static <T extends View> T $(View view, int id) {
- return (T) view.findViewById(id);
- }
- /**
- *
- * 公共的Toast消息显示方法(屏幕下方),解决多次调用时,多层覆盖的问题。不推荐使用此方式显示信息
- *
- * @param context
- * @param msg
- * @param duration
- */
- public static void showBottomMsg(Handler handler, final Context context, final String msg, final int duration) {
- handler.post(new Runnable() {
- @Override
- public void run() {
- if (bootom != null) {
- bootom.setText(msg);
- bootom.setDuration(duration);
- } else
- bootom = Toast.makeText(context, msg, duration);
- bootom.show();
- }
- });
- }
- /**
- *
- * 公共的Toast消息显示方法(屏幕中间),解决多次调用时,多层覆盖的问题。不推荐使用此方式显示信息
- *
- * @param context
- * @param msg
- * @param duration
- */
- public static void showCenterMsg(Handler handler, final Context context, final String msg, final int duration) {
- handler.post(new Runnable() {
- @Override
- public void run() {
- if (center != null) {
- center.setText(msg);
- center.setDuration(duration);
- } else
- center = Toast.makeText(context, msg, duration);
- center.setGravity(Gravity.CENTER, center.getXOffset() / 2, center.getYOffset() / 2);
- center.show();
- }
- });
- }
- /**
- *
- * 运行Shell命令
- *
- * @param cmd
- */
- public static void execShell(String cmd) {
- try {
- Process p = null;
- p = Runtime.getRuntime().exec("/system/xbin/su");
- OutputStream outputStream = p.getOutputStream();
- DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
- System.out.println("execShell>" + cmd);
- dataOutputStream.writeBytes(cmd + "\\n");
- dataOutputStream.writeBytes("exit\\n");
- dataOutputStream.flush();
- dataOutputStream.close();
- outputStream.close();
- p.waitFor();
- } catch (Exception e) {
- }
- }
- /**
- * 判断是否为合法IP
- *
- * @return the ip
- */
- public static boolean isIP(String ipAddress) {
- String ip = "((?:(?:25[0-5]|2[0-4]\\\\d|((1\\\\d{2})|([1-9]?\\\\d)))\\\\.){3}(?:25[0-5]|2[0-4]\\\\d|((1\\\\d{2})|([1-9]?\\\\d))))";
- Pattern pattern = Pattern.compile(ip);
- Matcher matcher = pattern.matcher(ipAddress);
- return matcher.matches();
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1101201614395.html
来源: http://www.codesnippet.cn/detail/1101201614395.html