常用方法1

1)判断手机号是否正确
2)获取屏幕分辨率
3)获取用户IP
4)获取网络信息
5)获取用户手机号码

  1. 将String 变为Date类型
    7)格式化显示数字,例如0—23格式化为00 — 23
    8)根据年月获取对应的天数
  2. AlertDialog 弹出框使用
    10) 获得圆角图片的方法
    11) 获得带倒影的图片方法
    12)将Drawable转化为Bitmap
    13)放大缩小图片
    14)根据屏幕分辨率等比例缩放
    15)给图片加边框,并返回边框后的图片
    16)字体闪烁动画,使用线程和Timer实现
    17)彩色圆角按钮
    18)显示当前时间
    19)动态添加有属性组件
    20)检查网络是否连接
    21)从资源文件中(asset)读取文本文档
    22)TextView文本添加下划线
    23)从历史栈中打开旧的Activity
    24)字符串超出给定文字则截取
    25)dp和px相互转换
    26)将传进的图片存储在手机上,并返回存储路径
    27)是否是正确的邮箱地址
    28)获取当前网络类型
    29)启动一个已安装应用(知道包名和入口activity)
    30)获取系统内的所有程序信息
    31)连续点击2次退出程序
    32)判断存储卡是否已插入
    33)得到软件版本信息
    34)根据URL获取bitmap
    35)隐藏app
    36)获取Andorid手机WIFI连接的Mac地址和IP地址
    37)判断字符串是否为数字串
    38)判断某一日期是否为今天,昨天或者更久
    39)创建抽象线程类,子类继承后可以直接使用线程
    40)根据url获取网络图片bitmap
    41)将字符串保存为json格式并使用ACache缓存
    42)获得Activity的版本名和版本号
    43)用相应的方法可以调用另一工程的Activity
    44)Android 读取 json 数据(遍历jsonarray和jsonboject)
    45)使用Timer控制一定时间内跳转到新的Activity
    46)常用正则表达式规则:
    47)自定义Button选择器
    48)自定义Android主题风格theme.xml方法
    49)混淆代码
    50)dialog样式
1)判断手机号是否正确:

  public static boolean IsPhoneNUmber(String phone){
        boolean result;
        if(phone == null 
                || phone.isEmpty()
                || phone.length() != 11)
        {
            result = false;
        }else{
            if(phone.startsWith("13")
                    || phone.startsWith("15")
                    || phone.startsWith("18")
                    || phone.startsWith("18")){
                result = true;
            }else{
                result =  false;
            }
        }
        return result;
    }   


2)获取屏幕分辨率
public static String getRatio(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        String ratio = dm.widthPixels + "*" + dm.heightPixels;
        return ratio;
    }

3)获取用户IP
public static String getUserIp() {
        try {
            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return null;
    }

4)获取网络信息
public static String getNetwork(Context context) {
        String netWork = null;
        boolean isWifi = false;
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info;
        if (connectivity != null) {
            info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
                        isWifi = true;
                        netWork = "wifi";
                    }
                }
            }
        }
        if (!isWifi) {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            int type = telephonyManager.getNetworkType();
            // NETWORK_TYPE_GPRS GPRS网络 1
            // NETWORK_TYPE_EDGE EDGE网络 2
            // NETWORK_TYPE_UMTS UMTS网络 3
            // NETWORK_TYPE_HSDPA HSDPA网络 8
            // NETWORK_TYPE_HSUPA HSUPA网络 9
            // NETWORK_TYPE_HSPA HSPA网络 10
            // NETWORK_TYPE_CDMA CDMA网络,IS95A �?IS95B. 4
            // NETWORK_TYPE_EVDO_0 EVDO网络, revision 0. 5
            // NETWORK_TYPE_EVDO_A EVDO网络, revision A. 6
            // NETWORK_TYPE_1xRTT 1xRTT网络 7
            switch (type) {
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
                netWork = "2G";
                break;
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                netWork = "3G";
                break;
            }
        }
        return netWork;
    }


5)获取用户手机号码
public static String getPhoneNumber(Context context) {
        String number = "";
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        number = telephonyManager.getLine1Number();
        return number;
    }

6) 将String 变为Date类型
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year_pick.getValue());
        c.set(Calendar.MONTH, month_pick.getValue()-1);
        c.set(Calendar.DAY_OF_MONTH, day_pick.getValue());
        c.set(Calendar.HOUR_OF_DAY, hour_pick.getValue());
        c.set(Calendar.MINUTE, min_pick.getValue());
        c.set(Calendar.SECOND, 0);
        
        Date select_date = c.getTime();

7)格式化显示数字,例如0—23格式化为00 — 23
  public String format(int value) {  
    String Str = String.valueOf(value);  
    if (value < 10) {  
        Str = "0" + Str;  
    }  
    return Str;  
}

 
 8)根据年月获取对应的天数

 public  int getDaysByYearMonth(int year, int month) {  
         
        Calendar a = Calendar.getInstance();  
        a.set(Calendar.YEAR, year);  
        a.set(Calendar.MONTH, month - 1);  
        a.set(Calendar.DATE, 1);  
        a.roll(Calendar.DATE, -1);  
        int maxDate = a.get(Calendar.DATE);  
        return maxDate;  
    }  

 9)AlertDialog 弹出框使用
        allMsgView = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.record_gather_numberpicker_dialog, null);  
        allMsg=new AlertDialog.Builder(this).create();
        allMsg.setCanceledOnTouchOutside(false);  
        allMsg.show();
        allMsg.getWindow().setContentView((RelativeLayout) allMsgView); 


10) 获得圆角图片的方法
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){   
            
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);   
        Canvas canvas = new Canvas(output);   
     
        final int color = 0xff424242;   
        final Paint paint = new Paint();   
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());   
        final RectF rectF = new RectF(rect);   
     
        paint.setAntiAlias(true);   
        canvas.drawARGB(0, 0, 0, 0);   
        paint.setColor(color);   
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);   
     
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));   
        canvas.drawBitmap(bitmap, rect, rect, paint);   
     
        return output;   
    }  

11) 获得带倒影的图片方法 
     public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap){   
       final int reflectionGap = 4;   
       int width = bitmap.getWidth();   
       int height = bitmap.getHeight();   
           
       Matrix matrix = new Matrix();   
       matrix.preScale(1, -1);   
           
       Bitmap reflectionImage = Bitmap.createBitmap(bitmap,0, height/2, width, height/2, matrix, false);   
           
       Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2), Config.ARGB_8888);   
           
       Canvas canvas = new Canvas(bitmapWithReflection);   
       canvas.drawBitmap(bitmap, 0, 0, null);   
       Paint deafalutPaint = new Paint();   
       canvas.drawRect(0, height,width,height + reflectionGap, deafalutPaint);   
           
       canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);   
           
       Paint paint = new Paint();   
       LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);   
       paint.setShader(shader);   
       // Set the Transfer mode to be porter duff and destination in   
       paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));   
      // Draw a rectangle using the paint with our linear gradient   
      canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()   
            + reflectionGap, paint);   
 
      return bitmapWithReflection;   
  }   

12)将Drawable转化为Bitmap
public static Bitmap drawableToBitmap(Drawable drawable){
      int width = drawable.getIntrinsicWidth();
      int height = drawable.getIntrinsicHeight();
      Bitmap bitmap = Bitmap.createBitmap(width, height,
      drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565);
      Canvas canvas = new Canvas(bitmap);
      drawable.setBounds(0,0,width,height);
      drawable.draw(canvas);
      return bitmap;
}

13)放大缩小图片
public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){   
        int width = bitmap.getWidth();   
        int height = bitmap.getHeight();   
        Matrix matrix = new Matrix();   
        float scaleWidht = ((float)w / width);   
        float scaleHeight = ((float)h / height);   
        matrix.postScale(scaleWidht, scaleHeight);   
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);   
        return newbmp;   
    }  

14)根据屏幕分辨率等比例缩放

        DisplayMetrics dm = this.getResources().getDisplayMetrics();
        PIC_WIDTH = (int) (PIC_WIDTH * dm.density);
        PIC_HEIGTH = (int) (PIC_HEIGTH * dm.density);

15)给图片加边框,并返回边框后的图片

public Bitmap getBitmapHuaSeBianKuang(Bitmap bitmap) {  
        float frameSize = 0.2f;  
        Matrix matrix = new Matrix();  
   
        // 用来做底图  
        Bitmap bitmapbg = Bitmap.createBitmap(bitmap.getWidth(),  
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);  
   
        // 设置底图为画布  
        Canvas canvas = new Canvas(bitmapbg);  
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG  
                | Paint.FILTER_BITMAP_FLAG));  
   
        float scale_x = (bitmap.getWidth() - 2 * frameSize - 2) * 1f  
                / (bitmap.getWidth());  
        float scale_y = (bitmap.getHeight() - 2 * frameSize - 2) * 1f  
                / (bitmap.getHeight());  
        matrix.reset();  
        matrix.postScale(scale_x, scale_y);  
   
        // 对相片大小处理(减去边框的大小)  
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),  
                bitmap.getHeight(), matrix, true);  
   
        Paint paint = new Paint();  
        paint.setColor(Color.WHITE);  
        paint.setStrokeWidth(1);  
        paint.setStyle(Style.FILL);  
   
        // 绘制底图边框  
        canvas.drawRect(  
                new Rect(0, 0, bitmapbg.getWidth(), bitmapbg.getHeight()),  
                paint);  
        // 绘制灰色边框  
        paint.setColor(Color.BLUE);  
        canvas.drawRect(  
                new Rect((int) (frameSize), (int) (frameSize), bitmapbg  
                        .getWidth() - (int) (frameSize), bitmapbg.getHeight()  
                        - (int) (frameSize)), paint);  
   
        canvas.drawBitmap(bitmap, frameSize + 1, frameSize + 1, paint);  
   
        return bitmapbg;  
    }  

16)字体闪烁动画,使用线程和Timer实现
    private int clo = 0;  
    public void spark() {  
        final TextView touchScreen = (TextView) findViewById(R.id.TextView01);// 获取页面textview对象  
        Timer timer = new Timer();  
        TimerTask taskcc = new TimerTask(){  
  
            public void run() {  
                runOnUiThread(new Runnable() {  
                    public void run() {  
                        if (clo == 0) {  
                            clo = 1;  
                            touchScreen.setTextColor(Color.TRANSPARENT); // 透明  
                        } else {  
                            if (clo == 1) {  
                                clo = 2;  
                                touchScreen.setTextColor(Color.RED);  
                            } else {  
                                clo = 0;  
                                touchScreen.setTextColor(Color.GREEN);  
                            }  
                        }  
                    }  
                });  
            }  
        };  
        timer.schedule(taskcc, 1, 300); // 参数分别是delay(多长时间后执行),duration(执行间隔)  
    }  

17)彩色圆角按钮



     
    
     
    
    
    
    
    




18)显示当前时间
 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
 sdf.format(new Date());

19)动态添加有属性组件

        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(  
                      ViewGroup.LayoutParams.FILL_PARENT, 64);  
  
      TextView text = new TextView(activity);  
      text.setLayoutParams(lp);  
      text.setTextSize(20);  
      text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);  
      text.setPadding(36, 0, 0, 0);  
      text.setText(s);

20)检查网络是否连接

    public boolean checkIntent(){
          ConnectivityManager mannager=(ConnectivityManager)
                this.getSystemService(CONNECTIVITY_SERVICE);
          NetworkInfo info=mannager.getActiveNetworkInfo();
          if(info==null || !info.isConnected()){
              return false;
          }
          if(info.isRoaming()){
              return true;
          }
          return true;
     }

21)从资源文件中(asset)读取文本文档
    ①
     InputStream in=getAssets().open("read_asset.txt");
     int size=in.available();
     byte[] buffer=new byte[size];//将输入流读到字节数组中(内存)
     in.read(buffer);
     in.close();
     String text=new String(buffer);

     ②
     public String getFromAssets(String fileName) {
        String result = "";
        try {
            InputStream in = getResources().getAssets().open(fileName);
            // 获取文件的字节数
            int lenght = in.available();
            // 创建byte数组
            byte[] buffer = new byte[lenght];
            // 将文件中的数据读到byte数组中
            in.read(buffer);
            result = EncodingUtils.getString(buffer, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



22)TextView文本添加下划线
    TextView textView = (TextView)findViewById(R.id.testView);    
  textView.setText(Html.fromHtml(""+"hahaha"+""));

23)从历史栈中打开旧的Activity
    如果历史栈中包含Activity,打开此Activity从栈中放到栈顶层而不是从新打开Activity
    Intent intent = new Intent(ReorderFour.this, ReorderTwo.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
  startActivity(intent);

24)字符串超出给定文字则截取
   public static String trim(String str,int limit) {// 字符串超出给定文字则截取
        String mStr = str.trim();
        return mStr.length() > limit ? mStr.substring(0, limit) : mStr;
    }

25)dp和px相互转换

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

26)将传进的图片存储在手机上,并返回存储路径
    /**
     * @param photo 要保存的图片
     * @param name 设置图片保存的名字
     * @param path  保存图片的文件夹名
     * @return  保存图片路径
     */
    public static String savePic(Bitmap photo, String name, String path) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 创建一个
        // outputstream
        // 来读取文件流
        photo.compress(Bitmap.CompressFormat.PNG, 100, baos);// 把 bitmap 的图片转换成
        // jpge
        // 的格式放入输出流中
        byte[] byteArray = baos.toByteArray();
        String saveDir = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        File dir = new File(saveDir + "/" + path);// 定义一个路径
        if (!dir.exists()) {// 如果路径不存在,创建路径
            dir.mkdir();
        }
        File file = new File(saveDir, name + ".png");// 定义一个文件
        if (file.exists())
            file.delete(); // 删除原来有此名字文件,删除
        try {
            file.createNewFile();
            FileOutputStream fos;
            fos = new FileOutputStream(file);// 通过 FileOutputStream 关联文件
            BufferedOutputStream bos = new BufferedOutputStream(fos); // 通过 bos
            // 往文件里写东西
            bos.write(byteArray);
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getPath();
    }


    
public static final String IMAGEPATH = Environment.getExternalStorageDirectory()+"/microcardio/careyou360/image/";
public static void savePic(Bitmap bm, String name) {
         File dirFile = new File(IMAGEPATH);  
            if(!dirFile.exists()){  
                dirFile.mkdir();  
            }  
            File myCaptureFile = new File(IMAGEPATH + name+ ".jpg");  
            BufferedOutputStream bos;
            try {
                bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);  
                bos.flush();  
                bos.close();  
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
    }




 27)是否是正确的邮箱地址

    public static boolean isEmail(String strEmail) {// 是否是正确的邮箱地址
        String checkemail = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern pattern = Pattern.compile(checkemail);
        Matcher matcher = pattern.matcher(strEmail);
        return matcher.matches();
    }


28)获取当前网络类型
   /**
     * 获取当前网络类型
     * 
     * @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
     */
    public int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (!StringUtils.isEmpty(extraInfo)) {
                if (extraInfo.toLowerCase().equals("cmnet")) {
                    netType = NETTYPE_CMNET;
                } else {
                    netType = NETTYPE_CMWAP;
                }
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }

 
 29)  启动一个已安装应用(知道包名和入口activity)

  ComponentName componentName=new ComponentName("应用的包名","应用入口activity"); 
  //ComponentName componentName=new ComponentName("com.hck.test", "com.hck.test.MainActivity");
  Intent intent=new Intent();
  intent.setComponent(componentName);
  startActivity(intent);

30)获取系统内的所有程序信息
   Intent mainintent = new Intent(Intent.ACTION_MAIN, null);
   mainintent.addCategory(Intent.CATEGORY_LAUNCHER);
   List   packageinfo = this.getPackageManager().getInstalledPackages(0);


31)连续点击2次退出程序
  
  if(event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
          long currentTime = System.currentTimeMillis();
          if((currentTime-touchTime)>=waitTime) {
             Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
             touchTime = currentTime;
             return true;
          }else {
             AppManager.getAppManager().appExit();
             finish();
             return false;
          }
            
          }
           return true;
   }

32)判断存储卡是否已插入
  public static boolean isExternalStorageAvailable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
        } else {
            return false;
        }
 }


33)得到软件版本信息

    public static String getSoftwareVersion(Context ctx) {
        String version = "";
        try {
            PackageInfo packageInfo = ctx.getPackageManager().getPackageInfo(
                    ctx.getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }


34)根据URL获取bitmap

     public static Bitmap getURLBitmap(String uriPic) throws Exception {
        URL imageUrl = null;
        Bitmap bitmap = null;
        try {
            imageUrl = new URL(uriPic);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(5 * 1000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(true);
            conn.setRequestMethod("POST");
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


 35)隐藏app
     public static void HiddenApp(Context ctx) {
        PackageManager pm = ctx.getPackageManager();
        ResolveInfo homeInfo = pm.resolveActivity(
                new Intent(Intent.ACTION_MAIN)
                        .addCategory(Intent.CATEGORY_HOME), 0);
        ActivityInfo ai = homeInfo.activityInfo;
        Intent startIntent = new Intent(Intent.ACTION_MAIN);
        startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
        ctx.startActivity(startIntent);
    }


 36)获取Andorid手机WIFI连接的Mac地址和IP地址

    public static String getInfo() {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();

        String maxText = info.getMacAddress();
        String ipText = intToIp(info.getIpAddress());
        String status = "";
        if (wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            status = "WIFI_STATE_ENABLED";
        }
        String ssid = info.getSSID();
        int networkID = info.getNetworkId();
        int speed = info.getLinkSpeed();
        return "mac:" + maxText + "\n\r" + "ip:" + ipText + "\n\r"
                + "wifi status :" + status + "\n\r" + "ssid :" + ssid + "\n\r"
                + "net work id :" + networkID + "\n\r" + "connection speed:"
                + speed + "\n\r";
    }


 37)判断字符串是否为数字串

   public static boolean isNumeric(String str){
      for (int i = str.length();--i>=0;){   
       if (!Character.isDigit(str.charAt(i))){
        return false;
       }
      }
      return true;
   }

 38)判断某一日期是否为今天,昨天或者更久
   public static String GetDateInfo(Date time) {

        String strInfo = "";
        if (time != null) {
            Date curDate = new Date();
            if (isSameDate(curDate, time)) {
                strInfo = "今天  ";
            } else if (isYesterday(curDate, time)) {
                strInfo = "昨天  ";
            } else {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日");
                strInfo = simpleDateFormat.format(time);
            }
        }

        return strInfo;
    }

    public static boolean isSameDate(Date date1, Date date2) {
        boolean result = false;
        Calendar c1 = Calendar.getInstance();
        c1.setTime(date1);

        Calendar c2 = Calendar.getInstance();
        c2.setTime(date2);

        if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH)) {
            result = true;
        }
        return result;
    }

    public static boolean isYesterday(Date currentDate, Date targetDate) {
        boolean result = false;
        Calendar c1 = Calendar.getInstance();
        c1.setTime(currentDate);
    
        Calendar c2 = Calendar.getInstance();
        c2.setTime(targetDate);
        
        return c1.get(Calendar.DATE) - c2.get(Calendar.DATE) == 1;
    }


 39)创建抽象线程类,子类继承后可以直接使用线程

  public abstract class AbstractThreadActivity extends AbstractActivity {
    
    public static final int OPERATION = -1; 
    

    public abstract Object doInThread(int operate, Object... objs) throws MCException;
    public abstract boolean handlerResult(boolean result, int operate, Object  obj);
    
    
    public class OperationThread extends Thread {   
        private int operate;
        private Object[] objs;
        
        public OperationThread(){}
        
        public OperationThread(int operate){
            this.operate = operate;
        }
        
        public OperationThread(int operate, Object... objs){
            this.operate = operate;
            this.objs = objs;
        }
        
        public void run() {                 
            Message msg = new Message();
            try{
                msg.what = operate;
                msg.obj = doInThread(operate, objs);
                msg.arg1 = MCException.MSG_NO_EXCEPTION;
            } catch (MCException e) {
                // TODO Auto-generated catch block
                msg.arg1 = e.getCode();         
                e.printStackTrace();
            }   
            OperationHandler.sendMessage(msg);          
        }
    }   
    
    Handler OperationHandler = new Handler(){  
      public void handleMessage(Message msg) { 
          boolean dealed = handlerResult(msg.arg1 == MCException.MSG_NO_EXCEPTION, msg.what, msg.obj);
          MCProgress.dismiss();
          
          if(!dealed && msg.arg1 != MCException.MSG_NO_EXCEPTION){          
              MCToast.show(MCMessage.getMessage(msg.arg1), AbstractThreadActivity.this);
          }
          
      } 
   };
}
 ************************************
 子类中使用父类线程
 第一步创建线程:
      new OperationThread(1, 123,"ml").start(); 
 第二步线程内部任务:
      @Override
      public Object doInThread(int operate, Object... objs) throws MCException {
        
        switch(operate){
        case 1:
            userMediator.updateAvatar((int)objs[0],(String)objs[1));  //(int)objs[0]=123  (String)objs[1)="ml"
            break;
        case USER_UPDATE: //其他线程
            userMediator.updateInfo((User)objs[0]);
            break;
        }
        return 2;
    }
 第三步线程完成后操作:
      @Override
     public boolean handlerResult(boolean result, int operate, Object obj) {
        // TODO Auto-generated method stub
        if(result){
            switch(operate){
            case 1:  
                 int num=(int)obj;  //线程的返回值2
                 
                break;
            }
        }
        return false;
    }
   
40)根据url获取网络图片bitmap

            URL url = new URL(web_img);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream inputStream = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

41)将字符串保存为json格式并使用ACache缓存
     private void stringTojson() {
        String name = ed_name.getText().toString().trim();
        String age = ed_age.getText().toString().trim();
        
        Btn18User user=new Btn18User();
        user.setName(name);
        user.setAge(age);
        
        JSONObject jsonObj = new JSONObject();
        try {
            jsonObj.put("name", user.getName());
            jsonObj.put("age", user.getAge());
        } catch (JSONException e) {         
            e.printStackTrace();
        }
        content=jsonObj.toString();
        tv.setText(content);
    }
  
42)获得Activity的版本名和版本号
    activity.getPackageManager().getPackageInfo("com.testSocket", 0).versionName;
    activity.getPackageManager().getPackageInfo("com.testSocket", 0).versionCode;

43)用相应的方法可以调用另一工程的Activity
    
    final Intent intent = new Intent(Intent.ACTION_MAIN, null);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.fuelgauge.PowerUsageSummary");
    intent.setComponent(cn);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity( intent);


44)Android 读取 json 数据(遍历jsonarray和jsonboject)
public String getJson(){   
        String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";//json字符串   
        try {   
            JSONObject result = new JSONObject(jsonstring);//转换为JSONObject   
            int num = result.length();   
            JSONArray nameList = result.getJSONArray("name");//获取JSONArray   
            int length = nameList.length();   
            String aa = "";   
            for(int i = 0; i < length; i++){//遍历JSONArray   
                Log.d("debugTest",Integer.toString(i));   
                JSONObject oj = nameList.getJSONObject(i);   
                aa = aa + oj.getString("name")+"|";   
                     
            }   
            Iterator it = result.keys();   
            String aa2 = "";   
            String bb2 = null;   
            while(it.hasNext()){//遍历JSONObject   
                bb2 = (String) it.next().toString();   
                aa2 = aa2 + result.getString(bb2);   
                     
            }   
            return aa;   
        } catch (JSONException e) {   
            throw new RuntimeException(e);   
        }   
    }


45)使用Timer控制一定时间内跳转到新的Activity
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frist);
        //1.创建Timer对象
        Timer timer = new Timer();
        //3.创建TimerTask对象
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Intent intent = new Intent(FristActivity.this,LoginActivity.class);
                startActivity(intent);
                finish();
            }
        };
        //2.使用timer.schedule()方法调用timerTask,定时3秒后执行run
        timer.schedule(timerTask, 3000);
    }

 46)常用正则表达式规则:


        String regex="^[0-9]*$";   //规则
        Pattern pat = Pattern.compile(regex);
        Matcher matcher = pat.matcher(content);   //content要匹配的内容
        boolean isMatched = matcher.matches(); 

   文本框输入内容控制:
     只能输入数字:"^[0-9]*$"
     只能输入n位的数字:"^\d{n}$"
     只能输入至少n位的数字:"^\d{n,}$"
     只能输入m~n位的数字:。"^\d{m,n}$"
     只能输入非零的正整数:"^\+?[1-9][0-9]*$"
     只能输入由26个英文字母组成的字符串:"^[A-Za-z]+$"
     只能输入由数字、26个英文字母或者下划线组成的字符串:"^\w+$"
     验证用户密码:"^[a-zA-Z]\w{5,17}$"  正确格式为:以字母开头,长度在6~18之间,只能包含字符、数字和下划线
     只能输入汉字:"^[\u4e00-\u9fa5]{0,}$"
     验证Email地址:"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"
     验证电话号码:"^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$"
     验证身份证号(15位或18位数字):"^\d{15}|\d{18}$"
     校验邮政编码: "/^[a-zA-Z0-9]{3,12}$/"


47)自定义Button选择器

  

    
        
            
            
            
            
        
    

    
        
            
            
            
            
        
    

           
        
            
            
            
            
        
    


48)自定义Android主题风格theme.xml方法:
  
   在工程中只需在androidmanifest.xml文件的Activity节点中加入android:theme="@style/Theme.CWJ" 属性,则这个Activity就使用了这种主题风格
    设置背景,所有字体颜色、大体大小和样式
    
    
      
   

 
 49)混淆代码

 -libraryjars libs/achartengine-1.1.0.jar
-libraryjars libs/AMap_2DMap_V2.3.0.jar
-libraryjars libs/AMap_Services_V2.3.0.jar
-libraryjars libs/Android_Location_V1.3.0.jar
-libraryjars libs/jpush-sdk-release1.7.0.jar
-libraryjars libs/gson-2.2.4.jar
-libraryjars libs/libammsdk.jar
-libraryjars libs/mta-sdk-1.6.2.jar
-libraryjars libs/open_sdk_r4066.jar
-libraryjars libs/umeng-analytics-v5.2.4.jar
-libraryjars libs/weibosdkcore.jar
-libraryjars libs/android-support-v4.jar  

-dontwarn com.amap.api.mapcore2d.**
-keep class com.amap.api.mapcore2d.** {*;}
 
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.support.v4.**
-keep public class com.android.vending.licensing.ILicensingService
-keep class com.tencent.mm.sdk.openapi.WXMediaMessage {*;}
-keep class com.tencent.mm.sdk.openapi.** implements com.tencent.mm.sdk.openapi.WXMediaMessage$IMediaObject {*;}

  
50)dialog样式



你可能感兴趣的:(常用方法1)