Android常用小知识


手机屏幕解锁的广播 action 是 Intent.ACTION_USER_PRESENT  (只能在代码中注册)

IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mUserPresentReceiver , filter);



SystemClock类

uptimeMillis()返回的是系统从启动到当前处于非休眠期的时间。

elapsedRealTime()返回的是系统从启动到现在的时间。

这个时间不可以修改,所以可以用来精确时间, SystemClock.elapsedRealtime() + delay来制造定时。

Intent i = new Intent();
i.setClass(this, PropellingService.class);
i.setAction(action);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + delay, duration, pi);

参考http://www.cnblogs.com/liyiran/p/5315069.html


我们在使用TextView显示内容的过程中,经常遇到需要显示的内容只有少许参数需要改变,比如:
距离过年还有xx天xx时xx秒,当我们在更新TextView的内容时,一般是这么写的:

TextView mTextView = this.findViewById(R.id.mTextView);
mTextView.setText("距离过年还有"+mDay+"天"+mMinute+"时"+mSecond+"秒");

如果你是用Android Studio开发的话,那么它应该送你以下的警告:

Do not concatenate text displayed with setText,use resource string with placeholders
[撇脚翻译:应使用资源字符串来显示文本占位符],这里所说的就是mDay、mMinute、mSecond这些变量了。
当然对于这些警告我们其实可以不理它们,它只是告诉我们这样写不规范,但如果我们要消除这个警告,
可以使用以下的实现:
string.xml中的资源声明
<string name="delay_time">距离过年还有%1$d天%2$d时%3$d秒</string>
在代码中的使用:

mTextView.setText(String.format(getResources().getString(R.string.delay_time),mDay,mMinute,mSecond));
常用格式:
%n$s--->n表示目前是第几个参数 (比如%1$s中的1代表第一个参数),s代表字符串
%n$d--->n表示目前是第几个参数 (比如%1$d中的1代表第一个参数),d代表整数
%n$f--->n表示目前是第几个参数 (比如%1$f中的1代表第一个参数),f代表浮点数

转载: http://www.jianshu.com/p/aeaacc092cf0



※EditText密码 明文和密文的切换

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    if(isChecked)
    {
        //设置密码为明文
        edittext.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    }else
    {
        //设置密码为密文
        edittext.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }
}

※格式化文件大小(利用android.text.format.Formatter.formatFileSize(@Nullable Context context,long sizeBytes)方法)




※将资源图片转化成inputStream

InputStream is = context.getResources().openRawResource(R.mipmap.ic_launch);


※一个textview显示不同颜色的字体

利用ForegroundColorSpan

        textview = (AppCompatTextView) findViewById(R.id.textview);
        SpannableString spannableString = new SpannableString("舞林至尊");
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.red)),0,1, SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.orange)),1,2, SPAN_INCLUSIVE_INCLUSIVE);
        textview.setText(spannableString);

        textview = (AppCompatTextView) findViewById(R.id.textview);
        /**
         * SPAN_INCLUSIVE_INCLUSIVE  它是用来标识在 Span 范围内的文本前后输入新的字符时是否把它们也应用这个效果
         * SPAN_INCLUSIVE_INCLUSIVE  前面包括,后面也包括  注意是对于输入的字符
         * */
        SpannableString spannableString = new SpannableString("图片-赤橙黄绿青蓝紫|图片");
        ImageSpan imageSpan = new ImageSpan(context,R.mipmap.b);
        spannableString.setSpan(imageSpan,0,2, SPAN_INCLUSIVE_EXCLUSIVE);// 图片span
        spannableString.setSpan(new BackgroundColorSpan(Color.GREEN),2,3, SPAN_INCLUSIVE_EXCLUSIVE);//背景色span
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.red)),3,4, SPAN_INCLUSIVE_INCLUSIVE);//前景色span
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.orange)),4,5, SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.yellow)),5,6, SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.green)),6,7, SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.cyan)),7,8, SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.blue)),8,9, SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context,R.color.purple)),9,10, SPAN_INCLUSIVE_INCLUSIVE);
        spannableString.setSpan(new UnderlineSpan(),3,10,SPAN_INCLUSIVE_INCLUSIVE);//下划线span
        spannableString.setSpan(new StrikethroughSpan(),10,11,SPAN_INCLUSIVE_INCLUSIVE);//中划线span
        spannableString.setSpan(new ImageSpan(context,R.mipmap.star),11,13,SPAN_INCLUSIVE_EXCLUSIVE);

        textview.setText(spannableString);



activity顶层

有时候会有这样的需求,比如退出登录了,要把其他activity都消亡掉。有很多种方法。

比如把所有activity都存起来一起消亡掉。

比如单例模式

这里介绍单例模式相差不多的。

        Intent intent = new Intent(context,LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

但是有个弊端,这里需要LoginActivity没有消亡掉,否则会没有效果。



手机邮箱身份证验证

手机

   /**
     * 验证是否是手机格式
     */
    public static boolean isMobileNO(String mobiles) {
        /*
        移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
	    联通:130、131、132、152、155、156、185、186
	    电信:133、153、180、189、(1349卫通)
	    总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9
	    只是现在有增加170号段
	    */
        String telRegex = "[1][3578]\\d{9}";//"[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

邮箱

    /**
     * 验证是否是邮箱格式格式
     */
    public static boolean isEmailAdd(String email) {
        String emailRegex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        if (TextUtils.isEmpty(email))
            return false;
        else
            return email.matches(emailRegex);
    }
身份证

介绍一个https://github.com/BestSingerInSiHui/CheckAllUtilsDemo

※下载代码

/**
	 * 从服务器下载apk
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static File getFileFromServer(String path) throws Exception {
		// 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);

			// 获取到文件的大小
//			int fileSize = conn.getContentLength();
//			int newFileSize = FormetFileSize(fileSize);
//			pd.setMax(newFileSize);

			InputStream is = conn.getInputStream();
			File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
			if(file.exists())
			{
				file.delete();
			}
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len;
			int total = 0;
			while ((len = bis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				total += len;
				// 获取当前已下载量
//				int newTotal = FormetFileSize(total);
//				pd.setProgress(newTotal);
//				pd.setProgressNumberFormat(newTotal + " kb/" + newFileSize + " kb");
			}
			fos.close();
			bis.close();
			is.close();
			return file;
		} else {
			return null;
		}
	}


推荐篇文章:Android 开发中不可不知的技巧


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值