安卓开发常用工具类utils
Posted Gradle官方文件
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓开发常用工具类utils相关的知识,希望对你有一定的参考价值。
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();
- 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-generatedmethodstub
this.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;
- 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;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri))
// ExternalStorageProvider
if (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];
// DownloadsProvider
else 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);
// MediaProvider
else 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 address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
// File
else 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();
创作打卡挑战赛
赢取流量/现金/CSDN周边激励大奖
以上是关于安卓开发常用工具类utils的主要内容,如果未能解决你的问题,请参考以下文章