轉:Android 開發技巧雜集

來源:互聯網
上載者:User

1.檢查是否有網路連接

  Java代碼

  1. public static boolean isNetworkAvailable(Context context) {

  2. ConnectivityManager cm = (ConnectivityManager) context.getSystemService(

  3. Context.CONNECTIVITY_SERVICE);

  4. NetworkInfo info = cm.getActiveNetworkInfo();

  5. return (info != null && info.isConnected());

  6. }

  public static boolean isNetworkAvailable(Context context) {

  ConnectivityManager cm = (ConnectivityManager) context.getSystemService(

  Context.CONNECTIVITY_SERVICE);

  NetworkInfo info = cm.getActiveNetworkInfo();

  return (info != null && info.isConnected());

  }

  2.全屏和無標題

  Java代碼

  1. // 全屏 ( No Statusbar )

  2. getWindow (). setFlags ( WindowManager . LayoutParams . FLAG _ FULLSCREEN ,

  3. WindowManager . LayoutParams . FLAG _ FULLSCREEN );

  4. // 無標題列 ( No Titlebar )

  5. requestWindowFeature ( Window . FEATURE _ NO _ TITLE );

  // 全屏 ( No Statusbar )

  getWindow (). setFlags ( WindowManager . LayoutParams . FLAG _ FULLSCREEN ,

  WindowManager . LayoutParams . FLAG _ FULLSCREEN );

  // 無標題列 ( No Titlebar )

  requestWindowFeature ( Window . FEATURE _ NO _ TITLE );

  3.使用ViewStub延遲展開視圖

  Java代碼

  1. 1 ) 定義 ViewStub

  2. < ViewStub android : id = "@+ id / stub _ import "

  3. android : inflatedId ="@+ id / panel _ import "

  4. android : layout ="@ layout / progress _ overlay "

  5. android : layout _ width =" fill _ parent "

  6. android:layout_height="wrap_content"

  7. android:layout_gravity="bottom"/>

  8. 2 )展開視圖

  9. findViewById(R.id.stub_import).setVisibility(View.VISIBLE);

  10. // 或者 擷取視圖

  11. View importPanel = ((ViewStub)

12. findViewById(R.id.stub_import)).inflate();

  1 ) 定義 ViewStub

  < ViewStub android : id = "@+ id / stub _ import "

  android : inflatedId ="@+ id / panel _ import "

  android : layout ="@ layout / progress _ overlay "

  android : layout _ width =" fill _ parent "

  android:layout_height="wrap_content"

  android:layout_gravity="bottom"/>

  2 )展開視圖

  findViewById(R.id.stub_import).setVisibility(View.VISIBLE);

  // 或者 擷取視圖

  View importPanel = ((ViewStub)

  findViewById(R.id.stub_import)).inflate();

  4.刪除視窗背景

  1) 編碼實現

  Java代碼

  1. public void onCreate(Bundle icicle){

  2. super.onCreate(icicle);

  3. setContentView(R.layout.mainview);

  4. // 刪除視窗背景

  5. getWindow().setBackgroundDrawable(null);

  6. ...

  7. }

  public void onCreate(Bundle icicle){

  super.onCreate(icicle);

  setContentView(R.layout.mainview);

  // 刪除視窗背景

  getWindow().setBackgroundDrawable(null);

  ...

  }

  2 )自訂佈景主題實現

  Java代碼

  1. < resources>

  2. < mce:style name="NoBackgroundTheme" parent="android:Theme">< !--

  3. < item name="android:windowBackground">@null< /item>

  4. -->< /mce:style>< style name="NoBackgroundTheme" parent="android:Theme" mce_bogus="1">< item name="android:windowBackground">@null< /item>< /style>

  5. < /resources>

  < resources>

  < mce:style name="NoBackgroundTheme" parent="android:Theme">< !--

  < item name="android:windowBackground">@null< /item>

  -->< /mce:style>< style name="NoBackgroundTheme" parent="android:Theme" mce_bogus="1">< item name="android:windowBackground">@null< /item>< /style>

  < /resources>

  6.橫豎屏切換時不重新載入 onCreate()

  為了防止橫豎屏切換時 Activity 重新載入 onCreate ,

  只需要在 Activity 的設定檔裡添加屬性:

  android:configChanges="orientation|keyboardHidden|navigation"

  7.半透明主題

  1.Resource source file location : res/values/styles.xml

  < style name="myTranslucentTheme" parent="android:style/Theme.Translucent">

  < item name="android:windowBackground">@drawable/bg< /item>

  < /style>

  其中 bg 為一張半透明圖片的索引

  2. 使用自訂半透明主題

  AndroidManifest.xml

  Java代碼

  1. < activity android:name=".WallpaperActivity"

  2. android:label="@string/wallpaper_titile"

  3. android:theme="@style/myTranslucentTheme">

  4. < /activity>

  < activity android:name=".WallpaperActivity"

  android:label="@string/wallpaper_titile"

  android:theme="@style/myTranslucentTheme">

  < /activity>

  8.擷取Android手機上的圖片和影片縮圖

  大家都知道Android從1.5開始剛插入SD卡時系統會調用MediaScanner服務進行後台掃描,索引新的歌曲、圖片和視頻等資訊,如果我們需要快速提取圖片和影片縮圖可以直接存取 android.provider.MediaStore.Images.Thumbnails 和android.provider.MediaStore.Video.Thumbnails這兩個資料庫,即可查詢出來縮圖

  如何判斷檔案呢? 可以通過Cursor遍曆資料庫,對比INTERNAL_CONTENT_URI欄位的值,這是一個Uri我們可以轉成String,這裡儲存著Android手機SD卡上的多媒體檔案完整路徑,

  有關具體的縮圖可以通過getThumbnail(ContentResolver cr, long origId, int kind, BitmapFactory.Options options) 或getThumbnail(ContentResolver cr, long origId, long groupId, int kind, BitmapFactory.Options options) 方法擷取,這兩種方法返回Bitmap類型,而縮圖的解析度可以從HEIGHT和WIDTH兩個欄位提取,在Android上縮圖分為兩種,通過讀取
KIND欄位來獲得,分別為MICRO_KIND和MINI_KIND 分別為微型和迷你兩種縮減模式,前者的解析度更低。這樣我們平時擷取檔案系統的某個圖片預覽時,可以直接調用系統縮圖,而不用自己重新計算。

  最後Android123提示大家,縮圖儲存在SD卡的DCIM目錄,裡面的.thumbnails是圖片的,而.video_thumbnails是視頻的,這兩個檔案夾為隱藏屬性,一般的檔案管理工具都可以看到。

  9.Android ANR介紹與避免

  很多初入Android開發的網友可能發現ANR的字樣,到底Android ANR是什麼呢? 其實ANR就是Application Not Responding的全稱,當某個應用處於長期假死狀態時Android系統會彈出一個視窗上面寫道,XXX is not responding給出兩個按鈕一個為force close一個為wait。

  可能觸發ANR的情況

  1. 長時間的I/O處理,比如讀寫大檔案,網路訪問時造成的阻塞。

  2. 執行耗時的運算,Android預設為超過5000ms即5秒開始彈出ANR視窗,某些應用可能首次執行時沒有緩衝十分耗時,可以通過Splash播放閃屏Logo等方式來延緩載入

  3. Service和appWidget中也要注意多線程的使用,除非它和Activity工作在不同的進程。

  避免ANR的方法

  1. 單獨開工作者線程,通過獨立的Thread或使用類似AsyncTask的方式來處理耗時的內容。

  2. 耗時的操作盡量分段處理,使用類似狀態機器的方法,類似Symbian的使用中的物件將一個複雜的事情,分段執行。

  3. UI線程中不要處理過多的內容,比如將一個5MB的文本,讓TextView去setText,要知道這種UI操作,沒有什麼好方法去解決的,所以Android123提示,遇到UI中需要執行複雜的操作,可以參考上面2提到的分段處理方式。

  10.AsyncTask對比Thread加Handler

  很多網友可能發現Android平台很多應用使用的都是AsyncTask,而並非Thread和Handler去更新UI,這裡 Android123給大家說下他們到底有什麼區別,我們平時應該使用哪種解決方案。從Android 1.5開始系統將AsyncTask引入到android.os包中,過去在很早1.1和1.0 SDK時其實官方將其命名為UserTask,其內部是JDK 1.5開始新增的concurrent庫,做過J2EE的網友可能明白並發庫效率和強大性,比Java原始的Thread更靈活和強大,但對於輕量級的使
用更為佔用系統資源。Thread是Java早期為實現多線程而設計的,比較簡單不支援concurrent中很多特性在同步和線程池類中需要自己去實現 很多的東西,對於分布式應用來說更需要自己寫調度代碼,而為了Android UI的重新整理Google引入了Handler和Looper機制,它們均基於訊息實現,有事可能訊息佇列阻塞或其他原因無法準確的使用。

  Android開發網推薦大家使用AsyncTask代替Thread+Handler的方式,不僅調用上更為簡單,經過實測更可靠一 些,Google在 Browser中大量使用了非同步任務作為處理耗時的I/O操作,比如下載檔案、讀寫資料庫等等,它們在本質上都離不開訊息,但是AsyncTask相比 Thread加Handler更為可靠,更易於維護,但AsyncTask缺點也是有的比如一旦線程開啟即dobackground方法執行後無法給線程 發送訊息,僅能通過預先設定好的標記來控制邏輯,當然可以通過線程的掛起等待標誌位的改變來通訊,對於某些應用Thread和Handler以及
Looper可能更靈活。

  11.android.os.Debug調試工具使用方法

  在Android軟體開發中最終的效能測試和調試顯得至觀重要,今天Android123和大家一起討論下Google送給我們的android.os.Debug類,使用起來比較簡單,我們先匯入 import android.os.Debug這個包。

  在需要開始跟蹤的地方加入 Debug.startMethodTracing(“/sdcard/cwj”);

  最終在停止調試的地方加入 Debug.stopMethodTracing();

  最終在sdcard上產生的cwj檔案我們可以用sdk ools中的traceview來查看啟動並執行結果。

  12.TextView多行本文滾動輕鬆實現

  Android中我們為了實現文本的滾動可以在ScrollView中嵌入一個TextView,其實TextView自己也可以實現多行滾動的,畢竟ScrollView必須只能有一個直接的子類布局。只要在layout中簡單設定幾個屬性就可以輕鬆實現

  Java代碼

  1. < TextView

  2. android:id="@+id/tvCWJ"

  3. android:layout_width="fill_parent"

  4. android:layout_height="wrap_content"

  5. android:scrollbars="vertical" < !--垂直捲軸 -->

  6. android:singleLine="false" < !--實現多行 -->

  7. android:maxLines="15" < !--最多不超過15行 -->

  8. android:textColor="#FF0000"

  9. />

  < TextView

  android:id="@+id/tvCWJ"

  android:layout_width="fill_parent"

  android:layout_height="wrap_content"

  android:scrollbars="vertical" < !--垂直捲軸 -->

android:singleLine="false" < !--實現多行 -->

  android:maxLines="15" < !--最多不超過15行 -->

  android:textColor="#FF0000"

  />

  當然我們為了讓TextView動起來,還需要用到TextView的setMovementMethod方法設定一個滾動執行個體,代碼如下

  Java代碼

  1. TextView tvAndroid123 = (TextView)findViewById(R.id.tvCWJ);

  2. tvAndroid123.setMovementMethod(ScrollingMovementMethod.getInstance()); // Android開發網提示相關的可以查看SDK中android.text.method分支瞭解更多

  TextView tvAndroid123 = (TextView)findViewById(R.id.tvCWJ);

  tvAndroid123.setMovementMethod(ScrollingMovementMethod.getInstance()); // Android開發網提示相關的可以查看SDK中android.text.method分支瞭解更多

  12.Widget簡單製作流程

  1、在 OnUpdate()中 定義一個 Intent

  Intent startActivityIntent = new Intent(context,WidgetLife.class);

  2、執行個體化一個 PendingIntent

  PendingIntent Pintent = PendingIntent.getActivity(context,0,startActivityIntent,0);

  3、執行個體RemoteView

  RemoteViews ActivityView = new RemoteViews(context.getPackageName(),R.layout.widget_layout);

  4、Button 事件

  ActivityView.setOnClickPendingIntent(R.id.Button,Pintent);

  5、更新Widget

  appWidgetManager.updateAppWidget(appWidgetIds,ActivityView);

  12.對話方塊【Dialog】去除白色邊框代碼

  邊框, Dialog, Android, 對話方塊, 代碼

  使用樣式檔案,在values 目錄下建立styles.xml檔案,編寫如下代碼:

  Java代碼

  1. < resources>

  2. < mce:style name="dialog" parent="@android:style/Theme.Dialog">< !--

  3. < item name="android:windowFrame">@null< /item>

  4. < item name="android:windowIsFloating">true< /item>

  5. < item name="android:windowIsTranslucent">false< /item>

  6. < item name="android:windowNoTitle">true< /item>

7. < item name="android:background">@android:color/black< /item>

  8. < item name="android:windowBackground">@null< /item>

  9. < item name="android:backgroundDimEnabled">false< /item>

  10.

  11. -->< /mce:style>< style name="dialog" parent="@android:style/Theme.Dialog" mce_bogus="1"> < item name="android:windowFrame">@null< /item>

  12. < item name="android:windowIsFloating">true< /item>

  13. < item name="android:windowIsTranslucent">false< /item>

  14. < item name="android:windowNoTitle">true< /item>

  15. < item name="android:background">@android:color/black< /item>

  16. < item name="android:windowBackground">@null< /item>

  17. < item name="android:backgroundDimEnabled">false< /item>

  18. < /style>

  19. < /resources>

  < resources>

  < mce:style name="dialog" parent="@android:style/Theme.Dialog">< !--

  < item name="android:windowFrame">@null< /item>

  < item name="android:windowIsFloating">true< /item>

  < item name="android:windowIsTranslucent">false< /item>

  < item name="android:windowNoTitle">true< /item>

  < item name="android:background">@android:color/black< /item>

  < item name="android:windowBackground">@null< /item>

  < item name="android:backgroundDimEnabled">false< /item>

  -->< /mce:style>< style name="dialog" parent="@android:style/Theme.Dialog" mce_bogus="1"> < item name="android:windowFrame">@null< /item>

  < item name="android:windowIsFloating">true< /item>

  < item name="android:windowIsTranslucent">false< /item>

< item name="android:windowNoTitle">true< /item>

  < item name="android:background">@android:color/black< /item>

  < item name="android:windowBackground">@null< /item>

  < item name="android:backgroundDimEnabled">false< /item>

  < /style>

  < /resources>

  調用時,使用AlerDialog的介面類,Dialog 介面編寫如下代碼:

  Java代碼

  1. Dialog dialog = new Dialog(SetActivity.this, R.style.dialog);

  2. dialog.setContentView(R.layout.test);

  3. dialog.show();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.