Android写代码中的一些小工具、方法

有的时候多次点击会弹出很多Toast,导致一直有Toast显示。一直消不掉。用下面方法可让Toast只显示一条,当再次需要Toast时只会改文本。

/**
 * Toast工具
 */
private static Toast toast;
public static void showToast(Context context,
                             String content) {
    if (toast == null) {
        toast = Toast.makeText(context,
                content,
                Toast.LENGTH_SHORT);
    } else {
        toast.setText(content);
    }
    toast.show();
}


禁止快速点击导致的一些系统崩溃。

/**
 * 禁止快速点击
 */
private static long lastClickTime;
public static boolean isFastDoubleClick(long timer) {
   long time = (new Date).getTime()
   long timeD = time - lastClickTime;
   if ( 0 < timeD && timeD < timer) {
      return true;
   }
   lastClickTime = time;
   return false;
}
public static boolean isFastDoubleClick() {
   return isFastDoubleClick(1000);
}

/**
 * 获取IMEI
 *
 * @param context
 * @return
 */
public static String getIMEI(Context context) {
   TelephonyManager telephonyManager = (TelephonyManager) context
         .getSystemService(Service.TELEPHONY_SERVICE);
   String imei = telephonyManager.getDeviceId();
   return imei;
}

/**
 * MD5加密
 *
 * @param inStr
 * @return
 */
public static String string2MD5(String inStr) {

   MessageDigest md5 = null;
   try {
      md5 = MessageDigest.getInstance("MD5");
   } catch (Exception e) {
      e.printStackTrace();
      return "";
   }
   char[] charArray = inStr.toCharArray();
   byte[] byteArray = new byte[charArray.length];

   for (int i = 0; i < charArray.length; i++)
      byteArray[i] = (byte) charArray[i];
   byte[] md5Bytes = md5.digest(byteArray);
   StringBuffer hexValue = new StringBuffer();
   for (int i = 0; i < md5Bytes.length; i++) {
      int val = ((int) md5Bytes[i]) & 0xff;
      if (val < 16)
         hexValue.append("0");
      hexValue.append(Integer.toHexString(val));
   }
   return hexValue.toString().toUpperCase();

}

/**
 * 获取版本号
 *
 * @param context
 * @return
 */
public static String getVersionName(Context context) {

   PackageManager pm = context.getPackageManager();
   try {
      PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
      return info.versionName;

   } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
      return "";
   }
}
public static int getVersionCode(Context context)//获取版本号(内部识别号)
{
   try {
      PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
      return pi.versionCode;
   } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return 0;
   }
}

/**
 * 禁止快速点击
 */
private static long lastClickTime;
public static boolean isFastDoubleClick(long timer) {
   long time = System.currentTimeMillis();
   long timeD = time - lastClickTime;
   if ( 0 < timeD && timeD < timer) {
      return true;
   }
   lastClickTime = time;
   return false;
}
public static boolean isFastDoubleClick() {
   return isFastDoubleClick(1000);
}
/**
 * 清理图片信息
 * @param dateNow
 * @param path
 */
public static void clearPic(Date dateNow,String path,long time){
   File file = new File(path);
   File[] files = file.listFiles();
   if (files.length > 0) {
      for (int i = 0; i < files.length; i++) {
         File myfile = files[i];
         String filename = myfile
               .getAbsoluteFile().getName();
         if(filename.length()<=20)continue;//文件格式不正常的图片则不操作
         Date fileDate = DateUtils.dateStringToDate(myfile
               .getAbsoluteFile().getName().substring(6, 20));
         if (dateNow.getTime() - fileDate.getTime() > time) {
            Log.d("MyTimerClearData", "删除图片文件"+path+"图片名字"+myfile);
            myfile.delete();

         } else {
            continue;
         }

      }
   }
}
// 获得可用的内存
@SuppressWarnings("deprecation")
public static long getmem_UNUSED(Context mContext) {
    final double memery = 0.20;//内存空间太少时
   File path = Environment.getDataDirectory();
   StatFs stat = new StatFs(path.getPath());
   long blockSize = stat.getBlockSize();
   long availableBlocks = stat.getAvailableBlocks();
   long useMemery = availableBlocks * blockSize / (1024 * 1024);
   //如果剩余空间小于20%则删除最久一天的数据
   if((float)useMemery/(float)getmem_ALL()<memery){
      ClearDataAndPic clearDataAndPic = new ClearDataAndPic();
      clearDataAndPic.clearDataMore();
   }
   return useMemery;

}

// 获得总体内存
@SuppressWarnings("deprecation")
public static long getmem_ALL() {
   File path = Environment.getDataDirectory();
   StatFs stat = new StatFs(path.getPath());
   long blockSize = stat.getBlockSize();
   long availableBlocks = stat.getBlockCount();
   return availableBlocks * blockSize / (1024 * 1024);

}

String 编码

/**
 * 将string转换成unicode
 *
 * @param string
 * @return
 */
public static String string2UTF8(String string) {
    if (string == null) string = "无信息";
    String descStr = "";
    try {
        descStr = new String(java.net.URLEncoder.encode(string, "utf-8").getBytes());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return descStr;
}
/**
 * 将unicode转换成string
 *
 * @param string
 * @return
 */
public static String UTF82string(String string) {
    if (string == null) string = "无信息";
    String descStr = "";
    try {
        descStr = new String(java.net.URLDecoder.decode(string, "utf-8").getBytes());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return descStr;
}



获得多点触摸的坐标点,可以对图片进行缩放

//多点触摸
if (MotionEventCompat.getPointerCount(event) > 1) {
    float touchX_1 = MotionEventCompat.getX(event, 0);
    float touchY_1 = MotionEventCompat.getY(event, 0);
    float touchX_2 = MotionEventCompat.getX(event, 1);
    float touchY_2 = MotionEventCompat.getY(event, 1);
    double cha = Math.sqrt(Math.pow( Math.abs(touchX_1-touchX_2),2)+ Math.pow( Math.abs(touchY_1-touchY_2),2));
    if(cha2!=0.0){
        double fangda = cha-cha2;
        if(Math.abs(fangda)>8){
            setZoom(zoom+(new Double(fangda*11/100).intValue()));

        }
    }

Android经典源码全集常用android小程序源码80个合集,可以做为你学习设计参考,每一个都是一个完整的小项目,里面都有源码,初学者学着用! 具体如下: GestureRecogniseSample GetPostSample GridAndImageSwitcherSample HandlerSample ImageButton Intent_ComponentSample Intent_DataSample Intent_TabHostSample IOStreamSample LauncherActivitySample LauncherSample Layer-listSample LinearLayoutSample ListViewSample ListViewTweenSample LocationManagerSample LockScreen LogicAlertDialogSample Matrix MatrixText MediaProviderSample MediaRecorder MenuItemSample MenuSample MenuXmlSample MockDialogSample MonitorPhone MoveBackgroundSample MusicBox MyLiveWallPaper PathEffectSample PlanGame PopupWindowSample ProgressBarSample ProgressDialogSample ProximityAlertSample RadioAndCheckbox RadioButtonAndCheckBox RatingBarSample RecordSound RegeditTable RegTable RelativeLayoutSample RequestCodeAndResponseCodeSample ScrollViewAndHorizontalViewSample SDCardSample SDFileExplorerSample SeekerBarSample SelecterDrawableSample SelecterSample SendSMSSample SensorSample ServiceSample ShaderSample ShapSample SharePreferencesSample SimpleAdapterSample SMSLisenter SpinnerSample SpinnerSample2 SQLiteOpenHelperSample SQLiteSample SSS.txt StartActivityToSecondActivitySimple StateListDrawableSample StyleSample SufaceVideoTest SundPoolSample SurfaceViewTest SweenedText TabHostSample TelephonyManagerSample TextToSpeechSample TextViewBackground TextViewSample TitleProgressBar ToastSample ToggleButton TouchCircle TweenAnimationSample UseIntentRebackHomeSample VibratorSample VideoViewSample VideoViewSample2 WallpaperManagerSample WindowThemeSample XmlResourceParserSample XmlValuesSample XmlValuesSample2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值