標籤:
1.android dp和px之間轉換public class DensityUtil { /** * 根據手機的解析度從 dip 的單位 轉成為 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根據手機的解析度從 px(像素) 的單位 轉成為 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
2.android 對話方塊樣式
<style name="MyDialog" parent="@android:Theme.Dialog"> <item name="android:windowNoTitle">true</item> <item name="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); int actual_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( final Context context, final Uri uri ) { 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 ) ) { Cursor cursor = context.getContentResolver().query( uri, new String[] { 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(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { //加入橫屏要處理的代碼 }else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { //加入豎屏要處理的代碼 } }
7.android 擷取mac地址1、<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 2、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();
9.android 擷取標題列狀態列高度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(new Runnable() { 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); } } <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: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方法可以擷取到程式顯示的地區,包括標題列,但不包括狀態列。 於是,我們就可以算出狀態列的高度了。 view plain Rect frame = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; 三、擷取標題列高度 getWindow().findViewById(Window.ID_ANDROID_CONTENT)這個方法擷取到的view就是程式不包括標題列的部分,然後就可以知道標題列的高度了。 view plain int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); //statusBarHeight是上面所求的狀態列的高度 int titleBarHeight = contentTop - statusBarHeight11.android 禁用home鍵盤 問題的提出 Android Home鍵系統負責監聽,捕獲後系統自動處理。有時候,系統的處理往往不隨我們意,想自己處理點擊Home後的事件,那怎麼辦? 問題的解決 先禁止Home鍵,再在onKeyDown裡處理按索引值,點擊Home鍵的時候就把程式關閉,或者隨你XXOO。 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(KeyEvent.KEYCODE_HOME==keyCode) android.os.Process.killProcess(android.os.Process.myPid()); return super.onKeyDown(keyCode, event); } @Override public void onAttachedToWindow() { // TODO Auto-generated method stub this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } 加許可權禁止Home鍵 <uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>
12.android 開機啟動public class StartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent startupintent = new Intent(context,StrongTracks.class); startupintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(startupintent); } } 2)<receiver android:name=".StartupReceiver"> <intent-filter> <!-- 系統啟動完成後會調用 --> <action android:name="android.intent.action.BOOT_COMPLETED"> </action> </intent-filter> </receiver> 13.android 控制對話方塊位置window =dialog.getWindow();// 得到對話方塊的視窗. WindowManager.LayoutParams wl = window.getAttributes(); wl.x = x;//這兩句設定了對話方塊的位置.0為中間 wl.y =y; wl.width =w; wl.height =h; wl.alpha =0.6f;// 這句設定了對話方塊的透明度 14.android 挪動dialog的位置Window mWindow = dialog.getWindow(); WindowManager.LayoutParams lp = mWindow.getAttributes(); lp.x = 10; //新位置X座標 lp.y = -100; //新位置Y座標 dialog.onWindowAttributesChanged(lp);15.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("是", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { 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("否", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }).show(); } return netSataus; } 16.android 設定apnContentValues values = new ContentValues(); values.put(NAME, "CMCC cmwap"); 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"17.android 調節螢幕亮度public void setBrightness(int level) { ContentResolver cr = getContentResolver(); Settings.System.putInt(cr, "screen_brightness", level); Window window = getWindow(); LayoutParams attributes = window.getAttributes(); float flevel = level; attributes.screenBrightness = flevel / 255; getWindow().setAttributes(attributes); }
18.android 重啟第一,root許可權,這是必須的 第二,Runtime.getRuntime().exec("su -c reboot"); 第三,模擬器上運行不出來,必須真機 第四,運行時會提示你是否加入列表 , 同意就好
19.android 資源uriandroid.resource://com.packagename/raw/xxxx20.android隱藏軟鍵盤setContentView(R.layout.activity_main); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
21.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) BitMap to inputStream: ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); InputStream isBm = new ByteArrayInputStream(baos .toByteArray()); (2)BitMap to byte[]: Bitmap defaultIcon = BitmapFactory.decodeStream(in); ByteArrayOutputStream stream = new ByteArrayOutputStream(); defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] bitmapdata = stream.toByteArray(); (3)Drawable to byte[]: Drawable d; // the drawable (Captain Obvious, to the rescue!!!) Bitmap bitmap = ((BitmapDrawable)d).getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, bitmap); byte[] bitmapdata = stream.toByteArray(); (4)byte[] to Bitmap : Bitmap bitmap =BitmapFactory.decodeByteArray(byte[], 0,byte[].length);23.發送指令out = process.getOutputStream(); out.write(("am start -a android.intent.action.VIEW -n com.android.browser/com.android.browser.BrowserActivity\n").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); }
24.Android判斷GPS是否開啟和強制幫使用者開啟GPShttp://blog.csdn.net/android_ls/article/details/8605931 引子:在我們的應用為使用者提供定位服務時,通常想為使用者提供精確點的定位服務,這是需要使用者配合的。我們必須先檢測使用者手機的GPS當前是否開啟,若沒開啟則彈出對話方塊提示。使用者若不配合我們也沒辦法,只能採用基站定位方式。如果我們的應用必須使用者開啟GPS才可使用,這時流氓一點的做法,就是強制幫使用者開啟GPS。
闡明概念:
定位服務GPS:全球衛星定位系統,使用24個人造衛星所形成的網路來三角定位接受器的位置,並提供經緯度座標。雖然GPS提供絕佳的位置的精確度,但定位的位置需要在可看見人造衛星或軌道所經過的地方。
定位服務AGPS:輔助全球衛星定位系統(英語:Assisted Global Positioning System,簡稱:AGPS)是一種GPS的運行方式。它可以利用手機基地站的資訊,配合傳統GPS衛星,讓定位的速度更快。用中文來說應該是網路輔助GPS定位系統。通俗的說AGPS是在以往通過衛星接受定位訊號的同時結合移動運營的GSM或者CDMA網路機站的定位資訊,就是一方面由具有AGPS的手機擷取來自衛星的定位資訊,而同時也要靠該手機透過中國移動的GPRS網路下載輔助的定位資訊,兩者相結合來完成定位。與傳統GPS(GlobalPositioningSystem全球定位系統)首次定位要2、3分鐘相比AGPS的首次定位時間最快僅需幾秒鐘,同時AGPS也徹底解決了普通GPS裝置在室內無法擷取定位資訊的缺陷。
一、檢測使用者手機的GPS當前是否開啟,,代碼如下:
[java] view plaincopy
/**
* 判斷GPS是否開啟,GPS或者AGPS開啟一個就認為是開啟的
* @param context
* @return true 表示開啟
*/
public static final boolean isOPen(final Context context) {
LocationManager locationManager
= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// 通過GPS衛星定位,定位層級可以精確到街(通過24顆衛星定位,在室外和空曠的地方定位準確、速度快)
boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// 通過WLAN或移動網路(3G/2G)確定的位置(也稱作AGPS,輔助GPS定位。主要用於在室內或遮蓋物(建築群或茂密的深林等)密集的地方定位)
boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps || network) {
return true;
}
return false;
}
二、強制幫使用者開啟GPS,代碼如下:
[java] view plaincopy
/**
* 強制幫使用者開啟GPS
* @param context
*/
public static final void openGPS(Context context) {
Intent GPSIntent = new Intent();
GPSIntent.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
GPSIntent.setData(Uri.parse("custom:3"));
try {
PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
} catch (CanceledException e) {
e.printStackTrace();
}
}
三、在AndroidManifest.xml檔案裡需要添加的許可權:
[html] view plaincopy
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Android編程實用代碼合集