1. 程式人生 > >Android之如何獲取手機程式列表以及程式相關資訊並啟動指定程式

Android之如何獲取手機程式列表以及程式相關資訊並啟動指定程式

效果圖:

程式列表:

啟動程式,獲取程式資訊:

程式碼如下:

建立一個AppInfo類來表示應用程式

<pre name="code" class="java">public class AppInfo {
	public CharSequence title;// 程式名
	public CharSequence packageName; // 程式包名
	Intent intent;// 啟動Intent
	public Drawable icon;// 程式圖示

	/*
	 * 設定啟動該程式的Intent
	 */
	final void setActivity(ComponentName className, int launchFlags) {
		intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		intent.setComponent(className);
		intent.setFlags(launchFlags);
	}

}

建立程式列表的介面卡:

/**
 * 程式列表介面卡
 * @author bill
 *
 */
public class ShowAppListAdapter extends BaseAdapter {
	private ArrayList<AppInfo> appList;
	private LayoutInflater inflater;
	
	public ShowAppListAdapter(Context context,ArrayList<AppInfo> appList,
			PackageManager pm) {
		this.appList = appList;
		inflater = LayoutInflater.from(context);
	}

	public int getCount() {
		return appList.size();
	}


	public Object getItem(int position) {
		return appList.get(position);
	}


	public long getItemId(int position) {
		return position;
	}


	public View getView(int position, View convertView, ViewGroup parent) {
		final AppInfo info = appList.get(position);
		ViewHolder holder = null;
		if(null == convertView){
			convertView = inflater.inflate(R.layout.app_list_item, null);
			holder = new ViewHolder();
			holder.lv_image = (ImageView) convertView.findViewById(R.id.lv_icon);
			holder.lv_name = (TextView) convertView.findViewById(R.id.lv_item_appname);
			holder.lv_packname = (TextView) convertView.findViewById(R.id.lv_item_packageame);
			convertView.setTag(holder);
		}
		else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.lv_image.setImageDrawable(info.icon);
		final CharSequence name = info.title;
		final CharSequence packName = info.packageName;
		holder.lv_name.setText(name);
		holder.lv_packname.setText(packName);
		return convertView;
	}
	private final static  class ViewHolder{
		ImageView lv_image;
		 TextView lv_name;
		 TextView lv_packname;
	}

	
}
public class MainActivity extends Activity {
	/*
	 * 應用程式集合
	 */
	private ArrayList<AppInfo> appInfos;
	private ListView lv_app;
	/*
	 * 管理應用程式包,並通過它獲取程式資訊
	 */
	private PackageManager pm;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_list);
		pm = getPackageManager();
		initView();
		new Thread(runable).start();
	}

	private void initView(){
		lv_app = (ListView) findViewById(R.id.app_list_view);
		lv_app.setOnItemClickListener(new AppDetailLinster());
	}

	
	private final Runnable runable = new Runnable() {

		public void run() {
			loadApplications();
			myHandler.obtainMessage().sendToTarget();
		}

	};

	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			lv_app.setAdapter(new ShowAppListAdapter(MainActivity.this,
					appInfos, pm));
			
			
		}

	};
	
	/**
	 * 載入應用列表
	 */
	private void loadApplications() {
		PackageManager manager = this.getPackageManager();
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		final List<ResolveInfo> apps = manager.queryIntentActivities(
				mainIntent, 0);
		Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));
		if (apps != null) {
			final int count = apps.size();
			if (appInfos == null) {
				appInfos = new ArrayList<AppInfo>(count);
			}
			appInfos.clear();
			for (int i = 0; i < count; i++) {
				AppInfo application = new AppInfo();
				ResolveInfo info = apps.get(i);
				application.title = info.loadLabel(manager);
				application.setActivity(new ComponentName(
						info.activityInfo.applicationInfo.packageName,
						info.activityInfo.name), Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				application.icon = info.activityInfo.loadIcon(manager);
				application.packageName = info.activityInfo.applicationInfo.packageName;
				appInfos.add(application);
			}
		}
	}
	
	
	/**
	 * 列表監聽類
	 * @author bill
	 *
	 */
	public final class AppDetailLinster implements OnItemClickListener {

		AlertDialog dialog;

		public void onItemClick(AdapterView<?> view, View arg1,
				final int position, long arg3) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);
			builder.setTitle("選項");
			builder.setItems(R.array.choice, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					final AppInfo appInfo = appInfos.get(position);
					switch (which) {
					case 0: // 啟動程式
						try {
							startApp(appInfo);
						} catch (Exception e) {
							
						}
						break;
					case 1: // 詳細資訊
						try {
							showAppDetail(appInfo);
						} catch (Exception e) {
							
						}
						break;
				
					}
					dialog.dismiss();
				}

				private void showAppDetail(AppInfo appInfo)
						throws Exception {
					final String packName = appInfo.packageName.toString();
					final PackageInfo packInfo = getAppPackinfo(packName);
					final String versionName = packInfo.versionName;
					final String[] apppremissions = packInfo.requestedPermissions;
					final String appName = appInfo.title.toString();
					Intent showDetailIntent = new Intent(MainActivity.this,
							ShowAppDetailActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("packagename", packName);
					bundle.putString("appversion", versionName);
					bundle.putStringArray("apppremissions", apppremissions);
					bundle.putString("appname", appName);
					showDetailIntent.putExtras(bundle);
					startActivity(showDetailIntent);

				}

				private void startApp(AppInfo appInfo)
						throws Exception {
					final String packName = appInfo.packageName.toString();
					final String activityName = getActivityName(packName);
					if (null == activityName) {
						Toast.makeText(MainActivity.this, "程式無法啟動",
								Toast.LENGTH_SHORT);
						return;
					}
					Intent intent = new Intent();
					intent.setComponent(new ComponentName(packName,
							activityName));
					startActivity(intent);
				}

			});
			dialog = builder.create();
			dialog.show();

		}

	}
	/**
	 * 獲取程式資訊
	 * @param packName
	 * @return
	 * @throws Exception
	 */
	public PackageInfo getAppPackinfo(String packName) throws Exception {
		return pm.getPackageInfo(packName, PackageManager.GET_ACTIVITIES
				| PackageManager.GET_PERMISSIONS);
	}
	
	/**
	 * 獲取啟動相關程式的Activity
	 * @param packName
	 * @return
	 * @throws Exception
	 */
	public String getActivityName(String packName) throws Exception {
		final PackageInfo packInfo = pm.getPackageInfo(packName,
				PackageManager.GET_ACTIVITIES);
		final ActivityInfo[] activitys = packInfo.activities;
		if (null == activitys || activitys.length <= 0) {
			return null;
		}
		return activitys[0].name;
	}
}

app_list.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/black" >



    <ListView
        android:id="@+id/app_list_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
      >
    </ListView>

</RelativeLayout>

app_list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="horizontal" android:layout_width="fill_parent"
	android:layout_height="wrap_content" android:gravity="center_vertical">
	
	<ImageView
		android:id="@+id/lv_icon"
		android:layout_width="48px"
		android:layout_height="48px"
		android:layout_marginTop="5px"
		android:layout_marginBottom="5px"
	></ImageView>
	<LinearLayout
		android:orientation="vertical"
		android:layout_width="wrap_content"
		android:layout_height="48px"
		android:paddingLeft="5px"
		>
		<TextView
			android:id="@+id/lv_item_appname"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:singleLine="true"
			android:textSize="16px"
			android:textStyle="bold"
			android:textColor="#fff"
		></TextView>
		
		<TextView
			android:id="@+id/lv_item_packageame"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:singleLine="true"
			android:textColor="#fff"
		></TextView>
		
		
	</LinearLayout>
</LinearLayout>
/**
 * 檢視應用資訊
 * @author bill
 *
 */
public class ShowAppDetailActivity extends Activity {

	private TextView tv_appname;
	private TextView tv_appversion;
	private TextView tv_packagename;
	private TextView tv_permission;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_detial);
		tv_appname = (TextView) findViewById(R.id.detail_app_name);
		tv_appversion = (TextView) findViewById(R.id.detail_app_version);
		tv_packagename = (TextView) findViewById(R.id.detail_app_packname);
		tv_permission = (TextView) findViewById(R.id.detail_app_permissions);
		Bundle bundle = this.getIntent().getExtras();
		String packagename=  bundle.getString("packagename");
		String appversion = bundle.getString("appversion");
		String appname = bundle.getString("appname");
		String[] appPremissions = bundle.getStringArray("apppremissions");
		StringBuilder sb = new StringBuilder();
		for(String s : appPremissions){
			sb.append(s);
			sb.append("\n");
		}
		tv_appname.setText(appname);
		tv_appversion.setText(appversion);
		tv_packagename.setText(packagename);
		tv_permission.setText(sb.toString());
	}
}


app_detial.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TableLayout 
        android:id="@+id/app_table"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TableRow 
              android:id="@+id/tableRow1"
      		  android:layout_width="wrap_content"
      		  android:layout_height="wrap_content"
            >
            <TextView 
                android:layout_width="wrap_content"
    			android:layout_height="wrap_content"
    			android:text="程式名字"
	    	/>
	    	<TextView 
	    	    android:layout_width="wrap_content"
	    		android:layout_height="wrap_content"
	    		android:id="@+id/detail_app_name"
	    	/>
        </TableRow>
         
        <TableRow 
	        android:id="@+id/tableRow2" 
	        android:layout_width="wrap_content" 
	        android:layout_height="wrap_content">
	    	 <TextView 
	    	     android:layout_width="wrap_content"
    			 android:layout_height="wrap_content"
    			 android:text="程式版本"
	    	/>
	    	<TextView 
	    	    android:layout_width="wrap_content"
	    		android:layout_height="wrap_content"
	    		android:id="@+id/detail_app_version"
	    	/>
	    </TableRow>
         <TableRow
	         android:id="@+id/tableRow3" 
	         android:layout_width="wrap_content" 
	         android:layout_height="wrap_content">
	    	 <TextView 
	    	     android:layout_width="wrap_content"
    			 android:layout_height="wrap_content"
    			 android:text="程式包名"
	    	/>
	    	<TextView 
	    	    android:layout_width="wrap_content"
	    		android:layout_height="wrap_content"
	    		android:id="@+id/detail_app_packname"
	    	/>
	    </TableRow>
	     <TableRow 
	         android:id="@+id/tableRow4"
	         android:layout_width="wrap_content" 
	         android:layout_height="wrap_content">
             <TextView 
                 android:layout_width="wrap_content"
    			 android:layout_height="wrap_content"
    			 android:text="程式許可權"
		    />
		    <TextView 
		        android:layout_width="wrap_content"
		    	android:layout_height="wrap_content"
		        android:id="@+id/detail_app_permissions"
		    	/>    
         </TableRow>
    </TableLayout>

</LinearLayout>


最後別忘了配置AndroidManifest。

相關推薦

Android如何獲取手機程式列表以及程式相關資訊啟動指定程式

效果圖: 程式列表: 啟動程式,獲取程式資訊: 程式碼如下: 建立一個AppInfo類來表示應用程式 <pre name="code" class="java">public class AppInfo { public

Android獲取手機UDID

最近做的一個專案中需要用到Android裝置唯一碼(UUID)來標識一臺裝置,Android中裝置唯一碼有很多,如:MAC地址、IMEI號(DeviceId)、IMSI號、ANDROID_ID、序列號(SerialNumber)等,但並不是所有裝置上都能穩定獲取到這些值。

Android獲取手機上的圖片和視訊縮圖thumbnails

【0】大家都知道Android從1.5開始剛插入SD卡時系統會呼叫MediaScanner服務進行後臺掃描,索引新的歌曲、圖片和視訊等資訊,如果我們需要快速提取圖片和視訊縮圖可以直接訪問 android.provider.MediaStore.Images.Thumbn

Android獲取手機中已安裝apk檔案資訊(PackageInfo、ResolveInfo)(應用圖片、應用名、包名等)

眾所周知,通過PackageManager可以獲取手機端已安裝的apk檔案的資訊,具體程式碼如下 PackageManager packageManager = this.getPackageManager();  List<PackageInfo> pac

獲取手機應用列表和APP應用資訊

各種獲取應用資訊小功能,做個筆記: /** * 獲取版本名 * * @param context * @return 獲取版本名 */ public static String getVersionName(Context

QTAndroid獲取手機感測器資料學習筆記

QT += core gui sensors positioning 其中sensors是獲取手機上感測器資料的元件,positioning是獲取位置資訊的元件 1、獲取陀螺儀感測器資料 #include <QGyroscope> QGyroscope *gyrosco

Android開發獲取手機硬體狀態資訊(CPU資訊/頻率/使用率、DDR頻率/使用率、電池瞬時電流/電壓/庫倫counter)

有時候我們想要知道當前手機的一些狀態資訊,可以使用app(root 或者系統簽名 )來顯示獲取。 OK,接下來看一下一些關鍵的程式碼。 我這裡使用的是高通的手機,不同硬體平臺的機型,其獲取資訊的節點可能不一樣。 /** * 獲取當前瞬時電流

android獲取聯絡人列表

public class SelectContactActivty extends Activity { private ListView lt_selectcontact; @Override public void onCreate(@Nulla

AndroidJNI① AS3.0以下DNK下載配置和第一個JNI程式

一、JNI介紹 JNI(Java Native Interface):一個協議,這個協議用來溝通java程式碼和外部的原生代碼(c/c++), 外部的c/c++程式碼也可以呼叫java程式碼。 1.1 C語言的優勢: ①效率上 C/C++是本地語言,比java更高效;

Android -ContentProvider獲取手機聯絡人

在做專案的時候,因為要用到我們自動獲取聯絡人的姓名和電話,就想到了ContentProvider分享資料的功能,這樣做既節省了時間, 也減少了我們輸入錯誤號碼的機率,所以,想在這裡把小demo分享給大家,方便以後要用的時候可以看看 我們

Android檢測手機插上和拔出USB盾以及插線和拔線

1、MyUsbManager.java public class MyUsbManager { public static final String ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE

Android筆記: 獲取手機的品牌、型號、Android系統版本號、IMEI、當前系統語言等工具類

最近在開發中,需要用到一些系統資訊,這裡我把這些方法寫成一個工具類方便以後複用,該工具類有以下6個功能: 1、獲取手機制造廠商 2、獲取手機型號 3、獲取手機系統當前使用的語言 4、獲取Andr

Android獲取螢幕大小

java 程式碼 import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import andr

Android獲取行動網路ip

1、獲取行動網路ip 2、程式碼 public String getLocalIpAddress() { try { for (Enumeration

android獲取全域性Context

1.介紹:Android提供了一個Application類,每當程式啟動的時候,系統就會自動將這個類進行初始化。因此我們                 可以定製一個自己的Application類,以便於管理程式內一

Android程式碼獲取手機品牌、手機型號、手機唯一序列號

獲取手機品牌:phone_brand = (TextView) findViewById(R.id.mobile_phone_brand); String brand = android.os.Build.BRAND; phone_brand.setText(brand);獲

Android 應用獲取手機的虛擬機器型別

Dalvik虛擬機器,是Google等廠商合作開發的Android移動裝置平臺的核心組成部分之一。它可以支援已轉換為.dex(即“Dalvik Executable”)格式的Java應用程式的執行。

Android檢視手機實時電流、電壓

就是從檔案中讀值,由於電流變化太快,顯示的是連續讀5次的平均值,直接上程式碼: public class MainActivity extends Activity { private boolean mIsStart = true; private To

Android獲取動態懸浮窗許可權

需要兩步: 一、在清單配置檔案中宣告許可權: <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> 二、程式碼申請許可權: private static fina

Android如何獲取手機各項資訊

1、使用Build獲取架構屬性 下面我們來根據原始碼看看通過Build這個類可以得到哪些配置資訊,具體就不解釋了,從命名基本可以理解其代表的屬性。 public class Build { //當一個版本屬性不知道時所設定的值。 publ