Android开发中一些小功能收藏起来,可以提高开发效率,平时的积累也是很重要的,这些功能其实不需要记住,收藏好,拿来就用,拿完即走。不多说了,抓紧保存备忘吧。

1.android dp和px之间转换

public class DensityUtil{ /***根据手机的分辨率从dip的单位转成为px(像素)*/public static int dip2px(Contextcontext,floatdpValue){final float scale=context.getResources().getDisplayMetrics().density;return(int)(dpValue*scale+0.5f);}/***根据手机的分辨率从px(像素)的单位转成为dp*/public static int px2dip(Contextcontext,floatpxValue){final float scale=context.getResources().getDisplayMetrics().density;return(int)(pxValue/scale+0.5f);}
}

2.android 对话框样式

<stylename="MyDialog"parent="@android:Theme.Dialog"><itemname="android:windowNoTitle">true</item><itemname="android:windowBackground">@color/ha</item>
</style>

3.android 根据uri获取路径

Uri uri=data.getData();
String[] proj={MediaStore.Images.Media.DATA};
Cursor actualimagecursor=managedQuery(uri,proj,null,null,null);
intactual_image_column_index=actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path=actualimagecursor.getString(actual_image_column_index);
File file=new File(img_path);

4.android 根据uri获取真实路径

public static String getRealFilePath(finalContextcontext,finalUriuri){if(null==uri)return null;final String scheme=uri.getScheme();String data=null;if(scheme==null)data=uri.getPath();else if(ContentResolver.SCHEME_FILE.equals(scheme)){data=uri.getPath();}else if(ContentResolver.SCHEME_CONTENT.equals(scheme)){Cursorcursor=context.getContentResolver().query(uri,newString[]{ImageColumns.DATA},null,null,null);if(null!=cursor){if(cursor.moveToFirst()){int index=cursor.getColumnIndex(ImageColumns.DATA);if(index>-1){data=cursor.getString(index);}}cursor.close();}}return data;
}

5.android 还原短信

ContentValues values=new ContentValues();
values.put("address","123456789");
values.put("body","haha");
values.put("date","135123000000");
getContentResolver().insert(Uri.parse("content://sms/sent"),values);

6.android 横竖屏切换

<activity android:name="MyActivity"
android:configChanges="orientation|keyboardHidden">
public void onConfigurationChanged(ConfigurationnewConfig){
super.onConfigurationChanged(newConfig);
if(this.getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE){
//加入横屏要处理的代码
}else if(this.getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT){
//加入竖屏要处理的代码
}}

7.android 获取mac地址

<uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>
private String getLocalMacAddress(){
WifiManager wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfo info=wifi.getConnectionInfo();
return info.getMacAddress();
}

8.android 获取sd卡状态

/**获取存储卡路径*/
File sdcardDir=Environment.getExternalStorageDirectory();
/**StatFs看文件系统空间使用情况*/
StatFs statFs=new StatFs(sdcardDir.getPath());
/**Block的size*/
Long blockSize=statFs.getBlockSize();
/**总Block数量*/
Long totalBlocks=statFs.getBlockCount();
/**已使用的Block数量*/
Long availableBlocks=statFs.getAvailableBlocks();
  1. Android获取状态栏和标题栏的高度
1.Android获取状态栏高度:
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。于是,我们就可以算出状态栏的高度了。Rect frame=new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight=frame.top;2.获取标题栏高度:getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。int contentTop=getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight=contentTop-statusBarHeight例子代码:
package com.cn.lhq;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
public class Main extends Activity{
ImageView iv;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv=(ImageView)this.findViewById(R.id.ImageView01);
iv.post(newRunnable(){
public void run(){viewInited();
}
});
Log.v("test","==ok==");
}
private void viewInited(){
Rect rect=new Rect();
Window window=getWindow();
iv.getWindowVisibleDisplayFrame(rect);
int statusBarHeight=rect.top;
int contentViewTop=window.findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
int titleBarHeight=contentViewTop-statusBarHeight;
//测试结果:ok之后100多ms才运行了
Log.v("test","=-init-=statusBarHeight="+statusBarHeight
+"contentViewTop="+contentViewTop+"titleBarHeight="
+titleBarHeight);
}}<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

10.android 获取各种窗体高度

//取得窗口属性
getWindowManager().getDefaultDisplay().getMetrics(dm);//窗口的宽度
int  screenWidth=dm.widthPixels;
//窗口高度
int screenHeight=dm.heightPixels;
textView=(TextView)findViewById(R.id.textView01);
textView.setText("屏幕宽度:"+screenWidth+"n屏幕高度:"+screenHeight);二、获取状态栏高度
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
于是,我们就可以算出状态栏的高度了。Rect frame=new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight=frame.top;
三、获取标题栏高度
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。
int contentTop=getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight=contentTop-statusBarHeight

11.android 禁用home键盘

问题的提出
AndroidHome键系统负责监听,捕获后系统自动处理。有时候,系统的处理往往不随我们意,想自己处理点击Home后的事件,那怎么办?问题的解决
先禁止Home键,再在onKeyDown里处理按键值,点击Home键的时候就把程序关闭,或者随你XXOO。
@Override
public boolean onKeyDown(int keyCode,KeyEvent event){
if(KeyEvent.KEYCODE_HOME==keyCode)android.os.Process.killProcess(android.os.Process.myPid());returnsuper.onKeyDown(keyCode,event);
}
@Override
public void onAttachedToWindow() {
//TODOAuto-generatedmethodstubthis.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);super.onAttachedToWindow();
}加权限禁止Home键
<uses-permissionandroid:name="android.permission.DISABLE_KEYGUARD"></uses-permission>

12.android 控制对话框位置

window=dialog.getWindow();//   得到对话框的窗口.
WindowManager.LayoutParamswl=window.getAttributes();
wl.x=x;//这两句设置了对话框的位置.0为中间
wl.y=y;
wl.width=w;
wl.height=h;
wl.alpha=0.6f;//这句设置了对话框的透明度

13.android 挪动dialog的位置

Window mWindow=dialog.getWindow();
WindowManager.LayoutParamslp=mWindow.getAttributes();
lp.x=10;//新位置X坐标
lp.y=-100;//新位置Y坐标
dialog.onWindowAttributesChanged(lp);

14.android 判断网络状态

<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"/>private boolean getNetWorkStatus(){
boolean netSataus=false;
ConnectivityManager cwjManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);cwjManager.getActiveNetworkInfo();if(cwjManager.getActiveNetworkInfo()!=null){
netSataus=cwjManager.getActiveNetworkInfo().isAvailable();
}if(!netSataus){
Builder b=new AlertDialog.Builder(this).setTitle("没有可用的网络")
.setMessage("是否对网络进行设置?");
b.setPositiveButton("是",newDialogInterface.OnClickListener(){
public void onClick(DialogInterfacedialog,intwhichButton){
Intent mIntent=new Intent("/");
ComponentName comp=new  ComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
mIntent.setComponent(comp);
mIntent.setAction("android.intent.action.VIEW");
startActivityForResult(mIntent,0);
}
}).setNeutralButton("否",newDialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int whichButton){
dialog.cancel();
}
}).show();
}
return netSataus;
}
  1. android 设置apn
ContentValues values=new ContentValues();
values.put(NAME,"CMCCcmwap");
values.put(APN,"cmwap");
values.put(PROXY,"10.0.0.172");values.put(PORT,"80");
values.put(MMSPROXY,"");
values.put(MMSPORT,"");
values.put(USER,"");
values.put(SERVER,"");
values.put(PASSWORD,"");
values.put(MMSC,"");
values.put(TYPE,"");
values.put(MCC,"460");
values.put(MNC,"00");
values.put(NUMERIC,"46000");
reURI=getContentResolver().insert(Uri.parse("content://telephony/carriers"),values);
//首选接入点"content://telephony/carriers/preferapn"

16.android 调节屏幕亮度

public void setBrightness(intlevel){ContentResolver cr=getContentResolver();Settings.System.putInt(cr,"screen_brightness",level);Windowwindow=getWindow();LayoutParams attributes=window.getAttributes();float flevel=level;attributes.screenBrightness=flevel/255;getWindow().setAttributes(attributes);
}

17.android 重启

第一,root权限,这是必须的
第二,Runtime.getRuntime().exec("su-creboot");
第三,模拟器上运行不出来,必须真机
第四,运行时会提示你是否加入列表,同意就好

18.android隐藏软键盘

setContentView(R.layout.activity_main);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE|
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

19.android隐藏以及显示软键盘以及不自动弹出键盘的方法

1、//隐藏软键盘
((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WidgetSearchActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);2、//显示软键盘,控件ID可以是EditText,TextView
((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(控件ID,0);
22.BitMap、Drawable、inputStream及byte[] 互转
(1)BitMaptoinputStream:
ByteArrayOutputStreambaos=newByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG,100,baos);
InputStreamisBm=newByteArrayInputStream(baos.toByteArray());(2)BitMaptobyte[]:
BitmapdefaultIcon=BitmapFactory.decodeStream(in);
ByteArrayOutputStreamstream=newByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG,100,stream);
byte[]bitmapdata=stream.toByteArray();
(3)Drawabletobyte[]:
Drawabled;//thedrawable(CaptainObvious,totherescue!!!)
Bitmapbitmap=((BitmapDrawable)d).getBitmap();
ByteArrayOutputStreamstream=newByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG,100,bitmap);
byte[]bitmapdata=stream.toByteArray();(4)byte[]toBitmap:
Bitmapbitmap=BitmapFactory.decodeByteArray(byte[],0,byte[].length);
23.发送指令
out=process.getOutputStream();
out.write(("amstart-aandroid.intent.action.VIEW-ncom.android.browser/com.android.browser.BrowserActivityn").getBytes());
out.flush();InputStream in=process.getInputStream();
BufferedReader re=new BufferedReader(new InputStreamReader(in));
String line=null;
while((line=re.readLine())!=null){
Log.d("conio","[result]"+line);
}

20.通过URI得到文件路径

    // 通用的从uri中获取路径的方法public static String getPath(final Context context, final Uri uri) {final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;// DocumentProviderif (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {// ExternalStorageProviderif (isExternalStorageDocument(uri)) {final String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];if ("primary".equalsIgnoreCase(type)) {return Environment.getExternalStorageDirectory() + "/" + split[1];}}// DownloadsProviderelse if (isDownloadsDocument(uri)) {final String id = DocumentsContract.getDocumentId(uri);final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(id));return getDataColumn(context, contentUri, null, null);}// MediaProviderelse if (isMediaDocument(uri)) {final String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];Uri contentUri = null;if ("image".equals(type)) {contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;} else if ("video".equals(type)) {contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;} else if ("audio".equals(type)) {contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;}final String selection = "_id=?";final String[] selectionArgs = new String[] { split[1] };return getDataColumn(context, contentUri, selection, selectionArgs);}}// MediaStore (and general)else if ("content".equalsIgnoreCase(uri.getScheme())) {// Return the remote addressif (isGooglePhotosUri(uri))return uri.getLastPathSegment();return getDataColumn(context, uri, null, null);}// Fileelse if ("file".equalsIgnoreCase(uri.getScheme())) {return uri.getPath();}return "";}public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {Cursor cursor = null;final String column = "_data";final String[] projection = { column };try {cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);if (cursor != null && cursor.moveToFirst()) {final int index = cursor.getColumnIndexOrThrow(column);return cursor.getString(index);}} finally {if (cursor != null)cursor.close();}return "";}public static boolean isExternalStorageDocument(Uri uri) {return "com.android.externalstorage.documents".equals(uri.getAuthority());}public static boolean isDownloadsDocument(Uri uri) {return "com.android.providers.downloads.documents".equals(uri.getAuthority());}public static boolean isMediaDocument(Uri uri) {return "com.android.providers.media.documents".equals(uri.getAuthority());}public static boolean isGooglePhotosUri(Uri uri) {return "com.google.android.apps.photos.content".equals(uri.getAuthority());}

21.判断当前是否在主线程

    public boolean isMainThread() {return Looper.getMainLooper().getThread() == Thread.currentThread();}

安卓开发常用工具类utils相关推荐

  1. android文件管理工具类,GitHub - RyanYans/Android-Utils: 安卓开发 常用 工具类 汇总

    天下文章一大抄,因为从开始学习到现在大约一年多 积攒的工具类.很多都是别人的. 但是也不知道是谁的了 如果涉及什么的问题.请联系我.我会做出相应修改: PS:不懂怎么用的,都可以看demo 一些都是已 ...

  2. java escape工具类_java开发常用工具类

    在Java中,,工具类定义了一组公共方法.你把你的类继承这些类或者实现这些接口,就可以使用这些类的方法了.下面给大家介绍一下十六种最常用的java开发常用工具类. 一. org.apache.comm ...

  3. Android开发常用工具类集合

    转载自:https://blog.csdn.net/xiaoyi_tdcq/article/details/52902844 Android开发常用工具类集合 android开发中为了避免重复造轮子, ...

  4. Android开发辅助工具类 Utils

    包括了各种工具类.辅助类.管理类等    都可以 在Git  里找到代码 来研究,深入 Awesome_API: https://github.com/marktony/Awesome_API/blo ...

  5. Android开发辅助工具类 Utils 汇总

    包括了各种工具类.辅助类.管理类等 Awesome_API: https://github.com/marktony/Awesome_API/blob/master/Chinese.md 收集中国国内 ...

  6. Android开发常用工具类

    来源于http://www.open-open.com/lib/view/open1416535785398.html 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前 ...

  7. java inputtools_Java后台开发常用工具类

    本文涉及的工具类部分是自己编写,另一部分是在项目里收集的.工具类涉及数据库连接.格式转换.文件操作.发送邮件等等.提高开发效率,欢迎收藏与转载. 数据库连接工具类 数据库连接工具类--仅仅获得连接对象 ...

  8. android开发常用工具类、高仿客户端、附近厕所、验证码助手、相机图片处理等源码...

    Android精选源码 android开发过程经常要用的工具类源码 Android类似QQ空间个人主页下拉头部放大的布局效果 Android高仿煎蛋客户端,Android完整项目 android帮你找 ...

  9. android开发常用工具类、高仿客户端、附近厕所、验证码助手、相机图片处理等源码

    Android精选源码 android开发过程经常要用的工具类源码 Android类似QQ空间个人主页下拉头部放大的布局效果 Android高仿煎蛋客户端,Android完整项目 android帮你找 ...

最新文章

  1. 欧拉定理 费马小定理
  2. MySQL主主配置说明
  3. 如何寻找蛋白和蛋白,基因和基因之间的相互作用---string
  4. SD-WAN — 云专线(企业入云)
  5. Django URL
  6. Ardino基础教程 7_蜂鸣器发声实验
  7. Python处理mat文件的三种方式
  8. yabailv 运放_运放入门
  9. php与go服务之间调用,PHP调用Go服务的正确方式 - Unix Domain Sockets
  10. 设置SQLServer数据库内存
  11. IE8的css hack
  12. Kafka 异步消息也会阻塞?记一次 Dubbo 频繁超时排查过程
  13. python dlib opencv人脸识别准确度_Dlib+OpenCV深度学习人脸识别
  14. 翱文中华灯谜大全 v1.1 免费下载--IT man
  15. arccatalog点要素显示不完_改变人际关系核心要素,不讨好不献媚,牢记这3点,受益一生...
  16. table添加一行且可编辑 vue_Vue使用AntDesign 表格可添加 可编辑行 可选择
  17. 【转自JULY大佬】程序员面试、算法研究、编程艺术、红黑树、机器学习5大系列集锦
  18. 早秋山居 --温庭筠[唐.五言律诗]
  19. 山东计算机技能高考试题,(完整版)2016山东春季高考技能考试-信息技术类专业试题...
  20. 怎么开发自己的微信小程序?

热门文章

  1. 公司自建电商系统对接Ariba PunchOut ----踩坑之路
  2. 在vue项目中 使用swiper轮播图的关于 在ios中图片白边闪屏踩坑记录
  3. 年收入100万的家庭如何买保险最划算?
  4. 如何检测手机整机的电流
  5. MySQL条件查询简单汇总
  6. 淘宝API官方商品、交易、订单、物流接口列表
  7. flash8绘制景深竹林
  8. 【论文笔记之 Speech Separation Overview】Supervised Speech Separation Based on Deep Learning-An Overview
  9. 以 NFT 为抵押品的借贷协议模式探讨
  10. Hive--hive一种通用的上亿级别的去重方法