Android實用代碼片段

jopen 12年前發布 | 51K 次閱讀 Android 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()
    二十一、獲取手機屏幕分辨率
DisplayMetrics  dm = new DisplayMereics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        float width = dm.widthPixels * dm.density;

        float height = dm.heightPixels * dm.density
    在這里問什么要乘以  dm.density   了,是因為通過dm.widthPixels的到的結果始終是320,不是真實的屏幕分辨率,所以要乘以dm.density得到真實的分辨率。
     二十二、在Activity里面播放背景音樂
   public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.mainlay);
                mediaPlayer = MediaPlayer.create(this, R.raw.mu);
                mediaPlayer.setLooping(true);
                mediaPlayer.start();

                      }


      二十三、讓程序的界面不隨機器的重力感應而翻轉

                 第一種方法,在manifast文件里面

<activity
  android:screenOrientation="portrait">
  </activity>

                  第二種,在代碼里面

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    二十四、使activity全屏顯示

requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,      
                WindowManager.LayoutParams. FLAG_FULLSCREEN);

        二十五、在RelativeLayout中使selector要注意點

         關于selector的使用方法,可以參考http://blog.csdn.net/aomandeshangxiao/article/details/6759576這篇文章,今天,遇到在RelativeLayout中添加background為selector后沒有反應的問題,尋摸了很長時間,一直沒有找到原因,其實只要加上一句代碼就完全可以解決:

RelativeLayout 里面加上android:clickable="true"

這樣,RelativLayout就會出現在selector里面定義的效果。


   二十六、顯示或隱藏虛擬鍵盤

顯示:
InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

隱藏:
InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
imm.hideSoftInputFromWindow(m_edit.getWindowToken(), 0);

   二十七、退出程序時清除通知中信息  

NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.cancelAll();

     二十八、創建快捷方式

Intent intent=new Intent();
//設置快捷方式的圖標
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.img));
//設置快捷方法的名稱
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "點擊啟動哥的程序");            //設置點擊快鍵圖標的響應操作
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,MainActivity.class));
//傳遞Intent對象給系統
setResult(RESULT_OK, intent);
finish();

 

   二十九、獲取文件中的類名:

String path = context.getPackageManager().getApplicationInfo(
                                        context.getPackageName(), 0).sourceDir;
                        DexFile dexfile = new DexFile(path);
                        Enumeration<String> entries = dexfile.entries();
                        while (entries.hasMoreElements()) {
                                String name = (String) entries.nextElement();
                                ......
                        }

 來自:http://blog.csdn.net/aomandeshangxiao/article/details/7006211

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!