android有用程式碼片段

來源:互聯網
上載者:User

          有時候,需要一些小的功能,找到以後,就把它貼到了部落格下面,作為留言,尋找起來很不方便,所以就整理一下,方便自己和他人。


         一、  擷取系統版本號碼:
PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);int versionCode=nfo.versionCodestring versionName=info.versionNam

       二、擷取系統資訊:

String archiveFilePath="sdcard/download/Law.apk";//安裝包路徑PackageManager pm = getPackageManager(); PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES); if(info != null){ ApplicationInfo appInfo = info.applicationInfo; String appName = pm.getApplicationLabel(appInfo).toString(); String packageName = appInfo.packageName; //得到安裝包名稱String version=info.versionName; //得到版本資訊 Toast.makeText(test4.this, "packageName:"+packageName+";version:"+version, Toast.LENGTH_LONG).show();Drawable icon = pm.getApplicationIcon(appInfo);//得到表徵圖資訊TextView tv = (TextView)findViewById(R.id.tv); //顯示表徵圖tv.setBackgroundDrawable(icon);



        三、擷取安裝路徑和已安裝程式列表

(1)android中擷取當前程式路徑getApplicationContext().getFilesDir().getAbsolutePath()(2)android取已安裝的程式列表List<PackageInfo> packageInfoList = getPackageManager().getInstalledPackages(0);



       四、擷取圖片、應用程式名稱、包名

PackageManager pManager = MessageSendActivity.this.getPackageManager(); List<PackageInfo> appList = Utils.getAllApps(MessageSendActivity.this);      for(int i=0;i<appList.size();i++) {          PackageInfo pinfo = appList.get(i);          ShareItemInfo shareItem = new ShareItemInfo();          //set Icon          shareItem.setIcon(pManager.getApplicationIcon(pinfo.applicationInfo));          //set Application Name shareItem.setLabel(pManager.getApplicationLabel(pinfo.applicationInfo).toString());         //set Package Name shareItem.setPackageName(pinfo.applicationInfo.packageName); }
         五、解決listview上 Item上有按鈕時 item本身不能點擊的問題:

1. 在item試圖上面添加代碼: android:descendantFocusability="blocksDescendants"2.在listview裡 添加代碼 android:focusable="true"
         六、不讓文字框輸入中文:

在xml檔案裡面

android:digits="1234567890qwertyuiopasdfghjklzxcvbnm`-=[]\;,./~!@#$%^*()_+}{:?&<>"'"這樣就不會輸入中文了。

        

         七、擷取螢幕寬高

DisplayMetrics displayMetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int height = displayMetrics.heightPixels; int width = displayMetrics.widthPixels;
         八、將TabWidget顯示在螢幕下方

設定TabWidget的屬性 android:layout_alignParentBottom="true"

為了讓tabHost顯示在下方,要將RadioGroup的layout_gravity設定為bottom,再將FrameLayout的 layout_weight設定為1,這樣就可以將RadioGroup撐到最下方。style="@style/main_tab_bottom"裡面定義了樣式檔案      

         九、擷取線程ID和線程名稱:

Log.v("@@@@@@@@@@",Thread.currentThread().getId()+" "+Thread.currentThread().getName());



        十、android中調用其它android應用

ComponentName comp = new ComponentName("com.Test","com.login.Main");  intent = new Intent();  intent.setComponent(comp);  intent.setAction("android.intent.action.VIEW");  startActivity(intent);
         十一、禁止軟鍵盤彈出

EditText有焦點(focusable為true)阻止IME彈出 editText.setInputType(InputType.TYPE_NULL); // 關閉軟鍵盤 當EidtText無焦點(focusable=false)時阻止IME彈出 

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

【Android】EditText標籤調用鍵盤
在xml檔案中EditText標籤有一個屬性android:editable="false"和android:numeric="integer"

android:numeric="integer"表示只允許輸入數字,此屬性可以限制使用者只能輸入數字內容。
android:editable表示是否可以輸入內容TRUE表示可以輸入,false表示不允許輸入內容;
當為android:editable="false"時,點擊輸入框,虛擬鍵盤是顯示不出來的,不過當設定了 android:editable=""屬性時,不管是false還是true,在其後加入android:numeric="integer"屬性時,是可以輸入數字內容了;這裡沒搞明白是怎麼回事,也許是numeric把前面的屬性覆蓋掉了。
當android:editable="false"時,在java類裡如果再規定EditText.setEnabled(true)時,虛擬鍵盤還是不會顯示的。
       十二、模擬器的各種規格與解析度對照:

單位:像素 WVGA854: 854*480WVGA800: 800*480HVGA: 480*320 QVGA: 320*240WQVGA432:432*240 WQVGA400:400*240 

    

     十三、調用Android其他Context的Activity
Context c = createPackageContext("chroya.demo", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);//載入這個類Class clazz = c.getClassLoader().loadClass("chroya.demo.Main");//建立一個執行個體Object owner = clazz.newInstance();//擷取print方法,傳入參數並執行Object obj = clazz.getMethod("print", String.class).invoke(owner, "Hello");

這個方法有兩個參數:
1、packageName  包名,要得到Context的包名
2、 flags  標誌位,有CONTEXT_INCLUDE_CODE和CONTEXT_IGNORE_SECURITY兩個選項。 CONTEXT_INCLUDE_CODE的意思是包括代碼,也就是說可以執行這個包裡面的代碼。CONTEXT_IGNORE_SECURITY的意思 是忽略安全警告,如果不加這個標誌的話,有些功能是用不了的,會出現安全警告。
       十四、android4.0Dialog風格小技巧

4.0上如果還用Theme.Dialog,只能說很土,跟整體UI風格差別很大

請使用android:theme="@android:style/Theme.Holo.DialogWhenLarge"

           十五、程式中安裝apk     

Intent intent = new Intent();       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);intent.setDataAndType(Uri.fromFile(“APK”),"application/vnd.android.package-archive");startActivity(intent);

其中“apk”為你要安裝的那個檔案。

         十六、擷取裝置型號、SDK版本及系統版本

String device_model = Build.MODEL; // 裝置型號  String version_sdk = Build.VERSION.SDK; // 裝置SDK版本  String version_release = Build.VERSION.RELEASE; // 裝置的系統版本  

       十七、圖片分析功能

public void SharePhoto(String photoUri,final Activity activity) {      Intent shareIntent = new Intent(Intent.ACTION_SEND);      File file = new File(photoUri);      shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));      shareIntent.setType("image/jpeg");      StartActivity(Intent.createChooser(shareIntent, activity.getTitle()));  }  

         十八、linux關機命令

在Windows下,按著電源鍵4秒強制關機,在Linux下強烈不建議這麼做。Windows由於是單使用者、“假多”任務的情況,所以即使你的電腦關機,也不會對別人造成影響。不過在Linux中,由於每個程式都是在後台執行的,因此,在你看不到的螢幕背後可能有很多人同時在你的主機上工作。而且,若不順利關機可能會造成檔案系統的損毀。所以,正常情況下,要關機時需要注意下面幾件事情:

(1)查看系統的使用狀態。

要看目前有誰線上,可以用who命令。要看網路的聯機狀態,可以用netstat-a命令。要看後台執行那個的程式可以執行ps-aux命令。

(2)通知線上使用者的關機時刻

這個時候可以使用shutdown命令

Shutdown命令:文法:shutdown[-t秒][-arkhncfF]時間 警告訊息-t:後面加描述表示過幾秒之後關機。-k:不是真的關機,僅僅發出警告訊息。-r:將系統服務停掉之後重啟。-h:將系統服務停掉之後立即關機。-f:關機並開機之後,強制跳過fsck的磁碟檢查。-F:系統重啟之後,強制進行fsck的磁碟檢查。-c:取消已經進行的shutdown命令內容。另外,重啟關機命令有reboot、halt、poweroff。其實在預設情況下,都完成一樣的工作。halt先調用shutdown,而shutdown最後調用halt。不過,shutdown可以根據目前已經啟動的服務來逐次關閉服務後才關機;而halt能夠在不理會目前系統情況下,進行硬體關機的特殊功能。除了這些,還有一個關機命令是init 0init是切換執行等級的命令。Linux共有7種執行等級,比較重要的是下面4種等級:run level 0:關機run level 3:純命令列模式run level 5:含有圖形介面模式run level 6:重啟

      十九、讓自己的應用不被kill掉可以在frameworks\base\services\java\com\android\server\am\ActivityManagerService.java這個類的forceStopPackage中加一個條件:

public void forceStopPackage(final String packageName) {        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)                != PackageManager.PERMISSION_GRANTED) {            String msg = "Permission Denial: forceStopPackage() from pid="                    + Binder.getCallingPid()                    + ", uid=" + Binder.getCallingUid()                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;            Slog.w(TAG, msg);            throw new SecurityException(msg);        }                long callingId = Binder.clearCallingIdentity();        try {            IPackageManager pm = ActivityThread.getPackageManager();            int pkgUid = -1;            synchronized(this) {                try {                    pkgUid = pm.getPackageUid(packageName);                } catch (RemoteException e) {                }                if (pkgUid == -1) {                    Slog.w(TAG, "Invalid packageName: " + packageName);                    return;                }                //begin:加入一個判斷條件                if (packageName.equals("你的進程名")) {                    return;                }                //end: 加入一個判斷條件                                forceStopPackageLocked(packageName, pkgUid);            }        } finally {            Binder.restoreCallingIdentity(callingId);        }    }

這樣的話在工作管理員裡可以保證KISS不掉的;
還有在這個方法上還有個方法clearApplicationUserData中保證如果是該進程就不讓調用forceStopPackage()方法。另:其他方法:

1,首先在你的service的onDestory方法裡面寫上啟動你自己的代碼,為什麼要寫這個?因為如果使用者是在設定->應用程式->正在運行服務這裡面殺掉你service的話會調用到onDestory方法的,這裡就可以啟動了,2:監聽螢幕關閉廣播,螢幕已關閉,就啟動服務。3:監聽螢幕解鎖廣播,一樣的道理,這樣,基本上,你的service就達到永不停止了。對使用者來說有點變態,但很多軟體都這樣。
     二十、EditText擷取焦點:
EditText.requestFoucus()
由於收集內容較多,所以決定每20條分為一篇文章。如有不便,敬請諒解!   查看其他部分:              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.