国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

安卓開發(fā)常用工具類utils

2019-11-08 00:03:44
字體:
供稿:網(wǎng)友

Android開發(fā)中一些小功能收藏起來,可以提高開發(fā)效率,平時的積累也是很重要的,這些功能其實不需要記住,收藏好,拿來就用,拿完即走。不多說了,抓緊保存?zhèn)渫伞?/p>

1.android dp和px之間轉(zhuǎn)換

public class DensityUtil{ /** *根據(jù)手機的分辨率從dip的單位轉(zhuǎn)成為px(像素) */ public static int dip2px(Contextcontext,floatdpValue){ final float scale=context.getResources().getDisplayMetrics().density; return(int)(dpValue*scale+0.5f); } /** *根據(jù)手機的分辨率從px(像素)的單位轉(zhuǎn)成為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 根據(jù)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 根據(jù)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卡狀態(tài)

/**獲取存儲卡路徑*/File sdcardDir=Environment.getExternalStorageDirectory();/**StatFs看文件系統(tǒng)空間使用情況*/StatFs statFs=new StatFs(sdcardDir.getPath());/**Block的size*/Long blockSize=statFs.getBlockSize();/**總Block數(shù)量*/Long totalBlocks=statFs.getBlockCount();/**已使用的Block數(shù)量*/Long availableBlocks=statFs.getAvailableBlocks();Android獲取狀態(tài)欄和標(biāo)題欄的高度1.Android獲取狀態(tài)欄高度:decorView是window中的最頂層view,可以從window中獲取到decorView,然后decorView有個getWindowVisibleDisplayFrame方法可以獲取到程序顯示的區(qū)域,包括標(biāo)題欄,但不包括狀態(tài)欄。 于是,我們就可以算出狀態(tài)欄的高度了。 Rect frame=new Rect();getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);int statusBarHeight=frame.top;2.獲取標(biāo)題欄高度: getWindow().findViewById(Window.ID_ANDROID_CONTENT)這個方法獲取到的view就是程序不包括標(biāo)題欄的部分,然后就可以知道標(biāo)題欄的高度了。 int contentTop=getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();//statusBarHeight是上面所求的狀態(tài)欄的高度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;@Overridepublic 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;//測試結(jié)果: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"><ImageViewandroid: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);二、獲取狀態(tài)欄高度decorView是window中的最頂層view,可以從window中獲取到decorView,然后decorView有個getWindowVisibleDisplayFrame方法可以獲取到程序顯示的區(qū)域,包括標(biāo)題欄,但不包括狀態(tài)欄。于是,我們就可以算出狀態(tài)欄的高度了。Rect frame=new Rect();getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);int statusBarHeight=frame.top;三、獲取標(biāo)題欄高度getWindow().findViewById(Window.ID_ANDROID_CONTENT)這個方法獲取到的view就是程序不包括標(biāo)題欄的部分,然后就可以知道標(biāo)題欄的高度了。int contentTop=getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();//statusBarHeight是上面所求的狀態(tài)欄的高度int titleBarHeight=contentTop-statusBarHeight

11.android 禁用home鍵盤

問題的提出AndroidHome鍵系統(tǒng)負(fù)責(zé)監(jiān)聽,捕獲后系統(tǒng)自動處理。有時候,系統(tǒng)的處理往往不隨我們意,想自己處理點擊Home后的事件,那怎么辦?問題的解決先禁止Home鍵,再在onKeyDown里處理按鍵值,點擊Home鍵的時候就把程序關(guān)閉,或者隨你XXOO。@Overridepublic boolean onKeyDown(int keyCode,KeyEvent event){if(KeyEvent.KEYCODE_HOME==keyCode) android.os.Process.killProcess(android.os.Process.myPid()); returnsuper.onKeyDown(keyCode,event);}@Overridepublic void onAttachedToWindow() {//TODOAuto-generatedmethodstub this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow();}加權(quán)限禁止Home鍵<uses-permissionandroid:name="android.permission.DISABLE_KEYGUARD"></uses-permission>

12.android 控制對話框位置

window=dialog.getWindow();//   得到對話框的窗口.WindowManager.LayoutParamswl=window.getAttributes();wl.x=x;//這兩句設(shè)置了對話框的位置.0為中間wl.y=y;wl.width=w;wl.height=h;wl.alpha=0.6f;//這句設(shè)置了對話框的透明度

13.android 挪動dialog的位置

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

14.android 判斷網(wǎng)絡(luò)狀態(tài)

<uses-permissionandroid: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("沒有可用的網(wǎng)絡(luò)").setMessage("是否對網(wǎng)絡(luò)進(jìn)行設(shè)置?");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 設(shè)置apnContentValues 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 調(diào)節(jié)屏幕亮度

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權(quán)限,這是必須的第二,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[] 互轉(zhuǎn)(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.發(fā)送指令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()); }
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 寿阳县| 大余县| 东台市| 虎林市| 奉节县| 兴和县| 和硕县| 南木林县| 郎溪县| 丰台区| 香格里拉县| 垣曲县| 信宜市| 安乡县| 哈尔滨市| 广灵县| 广南县| 合肥市| 逊克县| 马边| 太仆寺旗| 黔南| 金秀| 中西区| 东台市| 栖霞市| 富顺县| 普定县| 永胜县| 麻栗坡县| 屯昌县| 武汉市| 彭泽县| 阜康市| 潜山县| 叶城县| 东兰县| 伊金霍洛旗| 龙南县| 鄂温| 南溪县|