Android 開發有用代碼積累

來源:互聯網
上載者:User

標籤:

  Android開發需求變化快,開發週期要求盡量短,接下來一系列文章從實際使用出發總結一些常用的程式碼片段,便於尋找,也為後來人提供一份參考。

1.擷取Manifest的基本資料(升級頁面和軟體關於頁面一般會使用到)

Context mContext = XXXApplication.getInstance().getApplicationContext(); //擷取Application的Context ,當然也可以擷取當前的Activity的Context, Application一般是單例packageName = mContext.getPackageName(); //擷取包名,也就是manifest中的package選項的值PackageInfo info = mContext.getPackageManager().getPackageInfo(                mContext.getPackageName(), 0); //

String versionName = info.versionName;
int versionCode = info.versionCode;

2.擷取手機螢幕參數(對於螢幕適配很重要,畢竟Android手機的螢幕種類太多了)

Resources resources = XXXApplication.getInstance().getResources();float scale = resources.getDisplayMetrics().density;//螢幕密度因子,用於在px與dp之間轉化float scaledDensity = resources.getDisplayMetrics().scaledDensity;float disPlayWidth = resources.getDisplayMetrics().widthPixels;float disPlayHeight = resources.getDisplayMetrics().heightPixels;

  public static int dip2px(float dp) {
    return (int) (dp * scale + 0.5f);
  }

  public static int px2dip(float px) {
  return (int) (px / scale + 0.5f);
  }

  後面專門用篇文章來介紹一下我對不同螢幕適配的心得,今天就先介紹上面的代碼。

 

3. 隱藏軟鍵盤

 InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); 

//在含有EditText的頁面,有可能一進入該Activity軟鍵盤就彈出來,可以通過以下方法來禁止

 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

  

4. 安裝APK(比如說下載了升級軟體的時候,需要安裝替換舊版)

File apkfile = new File(apkFilePath); if (!apkfile.exists()) {            return;}  Intent i = new Intent(Intent.ACTION_VIEW); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");         mContext.startActivity(i);

  

 

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.