android有用代碼片段(一)

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

         一、  獲取系統版本號:

PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
int versionCode=nfo.versionCode
string 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)阻止輸入法彈出 editText.setInputType(InputType.TYPE_NULL); // 關閉軟鍵盤 
當EidtText無焦點(focusable=false)時阻止輸入法彈出 

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*480
WVGA800: 800*480
HVGA: 480*320 
QVGA: 320*240
WQVGA432: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 0
init是切換執行等級的命令。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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章