Android 常用工具类整理(持续更新)

编程入门 行业动态 更新时间:2024-10-13 18:26:25

Android <a href=https://www.elefans.com/category/jswz/34/1766763.html style=常用工具类整理(持续更新)"/>

Android 常用工具类整理(持续更新)

文章目录

  • 由于考了众多网络的中的代码,若有侵权,联系秒删
    • App相关(AppUtil )
    • 文件操作工具类
    • 统一日志
    • 一般正则表达式
    • 读取JSON文件
    • Dialog提示框工具类
        • 调用示例
    • 时间转换的工具类
    • Android 判断App是否是第一次启动

由于考了众多网络的中的代码,若有侵权,联系秒删

App相关(AppUtil )

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;/** * app相关辅助类 */ 
public class AppUtil { private AppUtil() { /* cannot be instantiated*/ throw new UnsupportedOperationException("cannot be instantiated");} /** * 获取应用程序名称 * * @param context * @return */ public static String getAppName(Context context) {PackageManager packageManager = context.getPackageManager();try { PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);int labelRes = packageInfo.applicationInfo.labelRes;return context.getResources().getString(labelRes);} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();} return null; } /** * 获取应用程序版本名称信息 * * @param context * @return 当前应用的版本名称 */ public static String getVersionName(Context context) {try { PackageManager packageManager = context.getPackageManager();PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);return packageInfo.versionName;} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();} return null; } /** * 获取应用程序的版本Code信息 * @param context * @return 版本code */ public static int getVersionCode(Context context) {try { PackageManager packageManager = context.getPackageManager();PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);return packageInfo.versionCode;} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();} return 0; } 
}

文件操作工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;/*** 文件操作工具类*/
public class FileUtil {/*** 在指定的位置创建指定的文件** @param filePath 完整的文件路径* @param mkdir 是否创建相关的文件夹* @throws Exception*/public static void mkFile(String filePath, boolean mkdir) throws Exception {File file = new File(filePath);file.getParentFile().mkdirs();file.createNewFile();file = null;}/*** 在指定的位置创建文件夹** @param dirPath 文件夹路径* @return 若创建成功,则返回True;反之,则返回False*/public static boolean mkDir(String dirPath) {return new File(dirPath).mkdirs();}/*** 删除指定的文件** @param filePath 文件路径** @return 若删除成功,则返回True;反之,则返回False**/public static boolean delFile(String filePath) {return new File(filePath).delete();}/*** 删除指定的文件夹** @param dirPath 文件夹路径* @param delFile 文件夹中是否包含文件* @return 若删除成功,则返回True;反之,则返回False**/public static boolean delDir(String dirPath, boolean delFile) {if (delFile) {File file = new File(dirPath);if (file.isFile()) {return file.delete();} else if (file.isDirectory()) {if (file.listFiles().length == 0) {return file.delete();} else {int zfiles = file.listFiles().length;File[] delfile = file.listFiles();for (int i = 0; i < zfiles; i++) {if (delfile[i].isDirectory()) {delDir(delfile[i].getAbsolutePath(), true);}delfile[i].delete();}return file.delete();}} else {return false;}} else {return new File(dirPath).delete();}}/*** 复制文件/文件夹 若要进行文件夹复制,请勿将目标文件夹置于源文件夹中* @param source 源文件(夹)* @param target 目标文件(夹)* @param isFolder 若进行文件夹复制,则为True;反之为False* @throws Exception*/public static void copy(String source, String target, boolean isFolder)throws Exception {if (isFolder) {(new File(target)).mkdirs();File a = new File(source);String[] file = a.list();File temp = null;for (int i = 0; i < file.length; i++) {if (source.endsWith(File.separator)) {temp = new File(source + file[i]);} else {temp = new File(source + File.separator + file[i]);}if (temp.isFile()) {FileInputStream input = new FileInputStream(temp);FileOutputStream output = new FileOutputStream(target + "/" + (temp.getName()).toString());byte[] b = new byte[1024];int len;while ((len = input.read(b)) != -1) {output.write(b, 0, len);}output.flush();output.close();input.close();}if (temp.isDirectory()) {copy(source + "/" + file[i], target + "/" + file[i], true);}}} else {int byteread = 0;File oldfile = new File(source);if (oldfile.exists()) {InputStream inStream = new FileInputStream(source);File file = new File(target);file.getParentFile().mkdirs();file.createNewFile();FileOutputStream fs = new FileOutputStream(file);byte[] buffer = new byte[1024];while ((byteread = inStream.read(buffer)) != -1) {fs.write(buffer, 0, byteread);}inStream.close();fs.close();}}}/*** 移动指定的文件(夹)到目标文件(夹)* @param source 源文件(夹)* @param target 目标文件(夹)* @param isFolder 若为文件夹,则为True;反之为False* @return* @throws Exception*/public static boolean move(String source, String target, boolean isFolder)throws Exception {copy(source, target, isFolder);if (isFolder) {return delDir(source, true);} else {return delFile(source);}}
}

统一日志

import android.util.Log;/*** Created by efan on 2017/4/13.*/public class Logger {//设为false关闭日志private static final boolean LOG_ENABLE = true;public static void i(String tag, String msg){if (LOG_ENABLE){Log.i(tag, msg);}}public static void v(String tag, String msg){if (LOG_ENABLE){Log.v(tag, msg);}}public static void d(String tag, String msg){if (LOG_ENABLE){Log.d(tag, msg);}}public static void w(String tag, String msg){if (LOG_ENABLE){Log.w(tag, msg);}}public static void e(String tag, String msg){if (LOG_ENABLE){Log.e(tag, msg);}}}

一般正则表达式

import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** @project baidamei* @author cevencheng <cevencheng@gmail>* @create 2012-11-15 下午4:54:42*/
public class RegexUtils {/*** 验证Email* @param email email地址,格式:zhangsan@zuidaima,zhangsan@xxx,xxx代表邮件服务商* @return 验证成功返回true,验证失败返回false*/ public static boolean checkEmail(String email) { String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; return Pattern.matches(regex, email); } /*** 验证身份证号码* @param idCard 居民身份证号码15位或18位,最后一位可能是数字或字母* @return 验证成功返回true,验证失败返回false*/ public static boolean checkIdCard(String idCard) { String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}"; return Pattern.matches(regex,idCard); } /*** 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港))* @param mobile 移动、联通、电信运营商的号码段*<p>移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡)*、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)</p>*<p>联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)</p>*<p>电信的号段:133、153、180(未启用)、189</p>* @return 验证成功返回true,验证失败返回false*/ public static boolean checkMobile(String mobile) { String regex = "(\\+\\d+)?1[34578]\\d{9}$"; return Pattern.matches(regex,mobile); } /*** 验证固定电话号码* @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447* <p><b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字,*  数字之后是空格分隔的国家(地区)代码。</p>* <p><b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号——* 对不使用地区或城市代码的国家(地区),则省略该组件。</p>* <p><b>电话号码:</b>这包含从 0 到 9 的一个或多个数字 </p>* @return 验证成功返回true,验证失败返回false*/ public static boolean checkPhone(String phone) { String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; return Pattern.matches(regex, phone); } /*** 验证整数(正整数和负整数)* @param digit 一位或多位0-9之间的整数* @return 验证成功返回true,验证失败返回false*/ public static boolean checkDigit(String digit) { String regex = "\\-?[1-9]\\d+"; return Pattern.matches(regex,digit); } /*** 验证整数和浮点数(正负整数和正负浮点数)* @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30* @return 验证成功返回true,验证失败返回false*/ public static boolean checkDecimals(String decimals) { String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; return Pattern.matches(regex,decimals); }  /*** 验证空白字符* @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B* @return 验证成功返回true,验证失败返回false*/ public static boolean checkBlankSpace(String blankSpace) { String regex = "\\s+"; return Pattern.matches(regex,blankSpace); } /*** 验证中文* @param chinese 中文字符* @return 验证成功返回true,验证失败返回false*/ public static boolean checkChinese(String chinese) { String regex = "^[\u4E00-\u9FA5]+$"; return Pattern.matches(regex,chinese); } /*** 验证日期(年月日)* @param birthday 日期,格式:1992-09-03,或1992.09.03* @return 验证成功返回true,验证失败返回false*/ public static boolean checkBirthday(String birthday) { String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; return Pattern.matches(regex,birthday); } /*** 验证URL地址* @param url 格式::80/xyang81/article/details/7705960? 或 :80* @return 验证成功返回true,验证失败返回false*/ public static boolean checkURL(String url) { String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?"; return Pattern.matches(regex, url); } /*** <pre>* 获取网址 URL 的一级域* </pre>* * @param url* @return*/public static String getDomain(String url) {Pattern p = Patternpile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);// 获取完整的域名// Pattern p=Patternpile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);Matcher matcher = p.matcher(url);matcher.find();return matcher.group();}/*** 匹配中国邮政编码* @param postcode 邮政编码* @return 验证成功返回true,验证失败返回false*/ public static boolean checkPostcode(String postcode) { String regex = "[1-9]\\d{5}"; return Pattern.matches(regex, postcode); } /*** 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小)* @param ipAddress IPv4标准地址* @return 验证成功返回true,验证失败返回false*/ public static boolean checkIpAddress(String ipAddress) { String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; return Pattern.matches(regex, ipAddress); } /*** 过滤器(示例 传入参数   哈哈哈+++111+++aaa 返回 哈哈哈111aaa)* 返回 中文--数字--字母*/public static String stringFilter(String str) throws PatternSyntaxException {// 只允许字母、数字和汉字String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";Pattern p = Patternpile(regEx);Matcher m = p.matcher(str);return m.replaceAll("").trim();}}

读取JSON文件

import android.content.Context;
import android.content.res.AssetManager;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;/*** <读取Json文件的工具类>** @author: 小嵩* @date: 2017/3/16 16:22*/public class GetJsonDataUtil {public String getJson(Context context, String fileName) {StringBuilder stringBuilder = new StringBuilder();try {AssetManager assetManager = context.getAssets();BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));String line;while ((line = bf.readLine()) != null) {stringBuilder.append(line);}} catch (IOException e) {e.printStackTrace();}return stringBuilder.toString();}
}

Dialog提示框工具类

调用示例
	final MyDialog myDialog = new MyDialog(context);myDialog.setMessage("内容");myDialog.setYesOnclickListener("确定", new MyDialog.onYesOnclickListener() {@Overridepublic void onYesClick() {myDialog.dismiss();}});myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {@Overridepublic void onNoClick() {myDialog.dismiss();}});myDialog.show();
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;import com.zhongshop.xdz.R;/*** Created by Lxx on 2018/4/20.*/public class MyDialog extends Dialog {private Button yes;private Button no;private TextView titleTv;private TextView messageTv;private String titleStr;private String messageStr;private String yesStr, noStr;private onNoOnclickListener noOnclickListener;private onYesOnclickListener yesOnclickListener;private boolean yesVisibility = false;private boolean noVisibility = false;private View lins;public void setNoOnclickListener(String str, onNoOnclickListener onNoOnclickListener) {if (str != null) {noStr = str;}this.noOnclickListener = onNoOnclickListener;}public void setYesOnclickListener(String str, onYesOnclickListener onYesOnclickListener) {if (str != null) {yesStr = str;}this.yesOnclickListener = onYesOnclickListener;}public MyDialog(Context context) {super(context, R.style.custom_dialog);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.layout_dialog);setCanceledOnTouchOutside(false);initView();initData();initEvent();}private void initEvent() {yes.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (yesOnclickListener != null) {yesOnclickListener.onYesClick();}}});no.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (noOnclickListener != null) {noOnclickListener.onNoClick();}}});}private void initData() {if (titleStr != null) {titleTv.setText(titleStr);}if (messageStr != null) {messageTv.setText(messageStr);}if (yesStr != null) {yes.setText(yesStr);}if (noStr != null) {no.setText(noStr);}if (yesVisibility) {yes.setVisibility(View.GONE);lins.setVisibility(View.GONE);}if (noVisibility) {no.setVisibility(View.GONE);lins.setVisibility(View.GONE);}}private void initView() {yes = (Button) findViewById(R.id.setting);no = (Button) findViewById(R.id.no);titleTv = (TextView) findViewById(R.id.title);messageTv = (TextView) findViewById(R.id.message);lins = findViewById(R.id.lins);}public void setTitle(String title) {titleStr = title;}public void setMessage(String message) {messageStr = message;}public void setYesVisibility(boolean visibility) {yesVisibility = visibility;}public void setNoVisibility(boolean visibility) {noVisibility = visibility;}public interface onYesOnclickListener {void onYesClick();}public interface onNoOnclickListener {void onNoClick();}
}

时间转换的工具类

import android.text.format.Time;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;/*** 这是一个时间转换的工具类* <p/>* 计算机能识别下面的字母:"yyyy-MM-dd DD HH:mm:ss SSS"* y代表的是年份,M代表的是月份,d代表的当月的第几天,D代表的是当年的第几天,* H代表的是小时数,m代表的是分钟数,s代表的秒数,S代表的是毫秒数。这个常识是需要我们记住的。* <p/>* *方法1:long getTimeLong()* 获取当前时间的毫秒数* <p/>* *方法2:int getTimeInt(String filter)* 输入某种时间格式的字符串,显示当前时间它的数据,比如输入getTimeInt(“DD”)获取今日是当前月的天数* <p/>* * 方法3:String getTimeString()* 获取当前时间的完整的格式,比如2016-11-11 8:20:20* <p/>* * 方法4:String getTimeString(long time)* 输入一个long类型的数据,获取一个完整格式的时间字符串,获取到的格式和方法三一样* <p/>* * 方法5: String getTimeString(long time, String filter)* 输入一个long类型的数据和一个自定义时间的格式的字符串,获取一个自定义的时间字符串,* 比如getTimeString(1111111L,“MM-dd”)获取的是毫秒数11111111的月分数和天数* <p/>* * 方法6:String getTimeString( String filter)* 输入某种时间格式的字符串,显示当前时间它的数据,比如输入getTimeString(“DD”)获取今日是当前月的天数* 这个方法和方法2相似,不过这里获取到的是字符串,只能用来做显示,而方法二获取到的是数字,可以用来显示和做相关运算。* * 方法7:String getTimeLong( String filter,String date)* 输入某种时间格式的字符串和对应时间格式的时间,显示它的毫秒数,比如输入getTimeString(“MM-dd”,“8-12”)获取8月12日的毫秒数* 这个方法一般用于对两个时间进行比较,从而得出哪一个时间比较久*/public class TimeUtil {/*** 获取当前时间的毫秒数*/public static long getTimeLong() {return System.currentTimeMillis();}/*** 获取当时时间的年,月,日,时分秒* 这里获得的时int类型的数据,要输入对应的格式* 比如要获得现在时间的天数值,* 使用getTime(“MM”),如果现在是2016年5月20日,取得的数字是5;*/public static int getTimeInt(String filter) {//SimpleDateFormat format = new SimpleDateFormat(filter);String time = format.format(new Date());return Integer.parseInt(time);}/*** 获取指定时间的年,月,日,时分秒* 这里获得的时int类型的数据,要输入完整时间的字符串和对应的格式* 比如要获得时间2016-12-12 14:12:10的小时的数值,* 使用getTime(“2016-12-12 14:12:10”,“HH”);得到14*/public static int getTimeInt(String StringTime, String filter) {//SimpleDateFormat format = new SimpleDateFormat(filter);String time = format.format(new Date(getTimeLong("yyyy-MM-dd HH:mm:ss", StringTime)));return Integer.parseInt(time);}/*** 获取当前时间的完整显示字符串*/public static final String getTimeString() {SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return format.format(new Date(getTimeLong()));}/*** 获得某个时间的完整格式的字符串* 输入的是某个时间的毫秒数,* 有些时候文件保存的时间是毫秒数,这时就需要转换来查看时间了!*/public static final String getTimeString(long time) {SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return format.format(new Date(time));}public static void main(String[] args){System.out.println(stampToDate(1568971789+""));}/*** 获得自定义格式的时间字符串* 输入的是某个时间的毫秒数,显示的可以是时间字符串的某一部分* 比如想要获得某一个时间的月和日,getTimeString(1111111111111,"MM-dd");*/public static final String getTimeString(long time, String filter) {SimpleDateFormat format = new SimpleDateFormat(filter);return format.format(new Date(time));}/*** 获得自定义格式的当前的时间的字符串* 比如当前时间2016年8月8日12时8分21秒,getTimeString("yyyy-MM-dd"),可以得到 2016-8-12*/public static final String getTimeString(String filter) {SimpleDateFormat format = new SimpleDateFormat(filter);return format.format(new Date(getTimeLong()));}/*** 获取某个时间的毫秒数,* 一般作用于时间先后的对比* 第一个参数是时间的格式,第二个参数是时间的具体值* 比如需要知道2016-6-20的毫秒数(小时和分钟默认为零),* getTimeLong("yyyy-MM-dd","2016-6-20")* 有时只有月日也是可以的,比如  getTimeLong("MM-dd","6-20") ,一般这个用来比较时间先后* 记住获得的毫秒数越大,时间就越近你*/public static Long getTimeLong(String filter, String date) {try {SimpleDateFormat format = new SimpleDateFormat(filter);Date dateTime = format.parse(date);return dateTime.getTime();} catch (Exception e) {e.printStackTrace();}return 0L;}/*** 获得某一个时间字符串中的局部字符串* 比如:String data= "2016-5-20 12:12:10",要获得后面的时间:5-20或 12:10* 使用:getTimeLocalString("yyyy-MM-dd HH:mm:ss",data,"MM-dd")   ,可以获得5-20* 如果是data="2016-5-20",要获得后面的5-20,* 也是一样的用法getTimeLocalString("yyyy-MM-dd ",data,"MM-dd")!*/public static String getTimeLocalString(String filter, String data, String filterInside) {Long timeLong = getTimeLong(filter, data);return getTimeString(timeLong, filterInside);}/*** 获取当前时间** @return*/public static String getNowTime() {String timeString = null;Time time = new Time();time.setToNow();String year = thanTen(time.year);String month = thanTen(time.month + 1);String monthDay = thanTen(time.monthDay);String hour = thanTen(time.hour);String minute = thanTen(time.minute);timeString = year + "-" + month + "-" + monthDay + " " + hour + ":" + minute;return timeString;}/*** 十一下加零** @param str* @return*/private static String thanTen(int str) {String string = null;if (str < 10) {string = "0" + str;} else {string = "" + str;}return string;}/*** 计算时间差** @param starTime 开始时间* @param endTime  结束时间*                 返回类型 ==1----天,时,分。 ==2----时* @return 返回时间差*/public static String getTimeDifference(String starTime, String endTime) {String timeString = "";SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");try {Date parse = dateFormat.parse(starTime);Date parse1 = dateFormat.parse(endTime);long diff = parse1.getTime() - parse.getTime();long day = diff / (24 * 60 * 60 * 1000);long hour = (diff / (60 * 60 * 1000) - day * 24);long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);long s = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);long ms = (diff - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000- min * 60 * 1000 - s * 1000);// System.out.println(day + "天" + hour + "小时" + min + "分" + s +"秒");long hour1 = diff / (60 * 60 * 1000);String hourString = hour1 + "";long min1 = ((diff / (60 * 1000)) - hour1 * 60);timeString = hour1 + "小时" + min1 + "分";//String.valueOf(day);System.out.println(day + "天" + hour + "小时" + min + "分" + s + "秒");} catch (ParseException e) {e.printStackTrace();}return timeString;}/** 将时间戳转换为时间** s就是时间戳*/public static String stampToDate(String s) {String res;SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//如果它本来就是long类型的,则不用写这一步long lt = new Long(s);Date date = new Date(lt * 1000);res = simpleDateFormat.format(date);return res;}/** 将时间转换为时间戳*/public static String dateToStamp(String s) throws ParseException {String res;SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");Date date = simpleDateFormat.parse(s);long ts = date.getTime();res = String.valueOf(ts);return res;}/*** 将时间戳转换为时间** s就是时间戳*/public static String sStampToDate(String s) {if(s.length()==10){s=s+"000";}String res;SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//如果它本来就是long类型的,则不用写这一步long lt = new Long(s);
//        Date date = new Date(lt * 1000);Date date = new Date(lt );res = simpleDateFormat.format(date);return res;}/** 将时间转换为时间戳*/public static String sDateToStamp(String s) throws ParseException {String res;SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");Date date = simpleDateFormat.parse(s.substring(0,s.length()-3));long ts = date.getTime();res = String.valueOf(ts);return res;}/*** 时间戳转换成字符窜** @param milSecond* @return*/public static String getDateToString(long milSecond) {// 10位的秒级别的时间戳String result1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(milSecond * 1000));// 13位的秒级别的时间戳// double time2 = 1515730332000d;// String result2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time2);// System.out.println("13位数的时间戳(毫秒)--->Date:" + result2);return result1;}/*** 时间戳转换成字符窜** @param milSecond* @return*/public static String getDateToString(long milSecond,int scanl) {// 10位的秒级别的时间戳String result1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(milSecond * scanl));// 13位的秒级别的时间戳// double time2 = 1515730332000d;// String result2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time2);// System.out.println("13位数的时间戳(毫秒)--->Date:" + result2);return result1;}}

Android 判断App是否是第一次启动

/*** 判断是否是首次启动**  此方法启动调用第一次是准确值,如果在一次启动中多次调用,即使是首次启动,第二次调用也会变成非首次启动,*  若需要多次获取,可以赋新值使用,每次启动只能调用此方法一次,赋值获取* @param context* @return*/
public static boolean isFirstStart(Context context) {SharedPreferences preferences = context.getSharedPreferences("NB_FIRST_START", 0);Boolean isFirst = preferences.getBoolean("FIRST_START", true);if (isFirst) {// 第一次preferences.edit().putBoolean("FIRST_START", false)mit();Log.d(TAG, "App第一次启动");return true;} else {return false;}
}/*** 判断是否是今日首次启动APP* @param context* @return*/
public static boolean isTodayFirstStartApp(Context context) {try {SharedPreferences preferences = context.getSharedPreferences("NB_TODAY_FIRST_START_APP", context.MODE_PRIVATE);String svaeTime = preferences.getString("startAppTime", "2020-01-08");String todayTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());if (!TextUtils.isEmpty(todayTime) && !TextUtils.isEmpty(svaeTime)) {if(!svaeTime.equals(todayTime)) {Log.d(TAG, "App今日第一次启动");preferences.edit().putString("startAppTime", todayTime)mit();return true;}}}catch (Exception e){Log.d(TAG, "是否为今日首次启动APP,获取异常:"+e.toString());return true;}return  false;}

Boolean(“FIRST_START”, false)mit();
Log.d(TAG, “App第一次启动”);
return true;
} else {
return false;
}
}

/**

  • 判断是否是今日首次启动APP

  • @param context

  • @return
    */
    public static boolean isTodayFirstStartApp(Context context) {
    try {
    SharedPreferences preferences = context.getSharedPreferences(“NB_TODAY_FIRST_START_APP”, context.MODE_PRIVATE);
    String svaeTime = preferences.getString(“startAppTime”, “2020-01-08”);
    String todayTime = new SimpleDateFormat(“yyyy-MM-dd”).format(new Date());

     if (!TextUtils.isEmpty(todayTime) && !TextUtils.isEmpty(svaeTime)) {if(!svaeTime.equals(todayTime)) {Log.d(TAG, "App今日第一次启动");preferences.edit().putString("startAppTime", todayTime)mit();return true;}}
    

    }catch (Exception e){
    Log.d(TAG, “是否为今日首次启动APP,获取异常:”+e.toString());
    return true;
    }
    return false;

}


更多推荐

Android 常用工具类整理(持续更新)

本文发布于:2024-02-08 21:12:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1675102.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常用工具   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!