Android開發之常用程式碼片段

來源:互聯網
上載者:User

標籤:android   http   io   os   ar   for   資料   sp   div   

1、設定視窗格式為半透明

getWindow().setFormat(PixelFormat.TRANSLUCENT);2、Android中在非UI線程裡更新View的不同方法:* Activity.runOnUiThread( Runnable )* View.post( Runnable )* View.postDelayed( Runnable, long )* Hanlder3、全螢幕顯示視窗requestWindowFeature(Window.FEATURE_NO_TITLE);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);4、取得螢幕大小方法A:WindowManager windowManager = getWindowManager();Display display = windowManager.getDefaultDisplay();hAndW[0] = display.getWidth();hAndW[1] = display.getHeight();方法B:DisplayMetrics dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);hAndW[0] = dm.widthPixels;hAndW[1] = dm.heightPixels;5、調瀏覽器 載入網址Uri uri = Uri.parse("http://www.google.com");Intent it = new Intent(Intent.ACTION_VIEW, uri);startActivity(it);6、取得記憶體大小ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();activityManager.getMemoryInfo(outInfo);//可用記憶體outInfo.availMem//是否在低記憶體狀態outInfo.lowMemory取得ScrollView的實際高度scrollview.getHeight()scrollview.getMeasuredHeight()scrollview.compute()scrollview.getLayoutParams().height7、監聽App安裝/卸載事件A.Define a class derived from class BroadcastReceiver;B.Register broadcast receiver;MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_INSTALL);filter.addAction(Intent.ACTION_PACKAGE_REMOVED);filter.addAction(Intent.ACTION_PACKAGE_ADDED);filter.addAction(Intent.ACTION_PACKAGE_CHANGED);filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);...filter.addDataScheme("package"); //This line is very important. Otherwise, broadcast can‘t be received.registerReceiver(myReceiver, filter);Notes: The package name is Intent.mData. Intent.mData is not available in SDK 1.0, but it can be retrieved by calling Intent.getDataString();8、取得IP地址A.//Connect via WIFI 通過wifiWifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);WifiInfo wifiInfo = wifiManager.getConnectionInfo();int ipAddress = wifiInfo.getIpAddress();B.//Connect via GPRS通過gprspublic String getLocalIpAddress(){try{for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){NetworkInterface intf = en.nextElement();for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){InetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress()){return inetAddress.getHostAddress().toString();}}}}catch (SocketException ex){Log.e(S.TAG, ex.toString());}return null;}9、ListView 後面adapter資料已更改,但是ListView沒有收到Notification首先,必須將 更新adapter資料的代碼放在:Handler.post(Runnable)方法中執行;然後,如果Adapter資料的來源如果是cursor(CursorAdapter)的話 可以cursor.requery一下,如果是別的可以強制調用一下notifyChange, notifyChange 會調用 invalidate 進行重繪;10、類比HOME鍵Intent i=new Intent(Intent.ACTION_MAIN);i.addCategory(Intent.CATEGORY_HOME);i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(i);11、設定焦點editText.setFocusable(true);editText.requestFocus();editText.setFocusableInTouchMode(true);12、去掉平板導航getWindow().getDecorView().setSystemUiVisibility(8);//只有某個特別機子有效13、PowerManager

PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "myLock");

wakeLock.acquire();

wakeLock.release();

 

下面定義的flag是在newWakeLock方法中要接收的參數,通過該flag,你可以定義系統的電源的展示效果。比如:
 *                                                  cpu       screen       keyboard
 * PARTIAL_WAKE_LOCK                  on         off             off
 * SCREEN_DIM_WAKE_LOCK          on         dim           off
 * SCREEN_BRIGHT_WAKE_LOCK   on         bright        off
 * FULL_WAKE_LOCK                       on         bright        bright

這些flag是相互排斥的,一次只能定義一個。

如果你持有PARTIAL_WAKE_LOCK鎖,不論任何定時器甚至是按下電源開關,cpu都將繼續運行,無法進入休眠狀態。除非你釋放掉它。
其他鎖的話,雖然cpu也在運行,但是當使用者按下電源開關時,裝置將立刻進入休眠狀態。

 正常情況下wakelocks實際上是沒有被開啟的,當需要時,它將通過特定的flag啟動螢幕和鍵盤。 比如在應用中,涉及到向使用者發送訊息時,需要讓使用者立刻看到。此時會點亮螢幕。當WakeLock鎖被釋放的時候,activity的定時器將被重設,這將導致螢幕亮更長的時間。

 

14、SharedPreferences

SharedPreferences sp = getSharedPreferences(Constant.SERVUCE_APP, MODE_PRIVATE);

sp.putString(key,values);

Editor edit = sp.edit();

edit.commit();//修改後要記得提交

 

15、SQLite

實現這個抽象類別SQLiteOpenHelper

DBHelper extends SQLiteOpenHelper

實現三個方法

DBHelper(Context context, String name, CursorFactory factory,int version, DatabaseErrorHandler errorHandler) 

context //上下文  name//資料庫名稱 version //資料庫的版本號碼 

 

onCreate(SQLiteDatabase db)

第一次建立DBHelper執行onCreate方法

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

SQLite版本變化時執行onUpgrade再執行onCreate

 

 

 

Android開發之常用程式碼片段

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.