异步获取已安装程序列表(PackageManager+AsyncTask)

来源:互联网 发布:手机老是弹出淘宝口令 编辑:程序博客网 时间:2024/06/10 01:42
不是异步的例子,显然有个延迟。
package com.ql.app;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.content.pm.ResolveInfo;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;public class ProcessorBarTest extends Activity {private ListView listview;private Context mContext;private List<String> mAppList;private ArrayAdapter mAdapter;private boolean mIsLoaded = false;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.screen_1);listview = (ListView)findViewById(R.id.listview);mContext = this;mAppList = new ArrayList<String>();mAdapter = new ArrayAdapter(mContext,android.R.layout.simple_list_item_1, mAppList);listview.setAdapter(mAdapter);// 获取已经安装程序列表PackageManager pm = mContext.getPackageManager();                //有入口&图标的一定就是应用Intent intent = new Intent(Intent.ACTION_MAIN, null);//入口就是应用intent.addCategory(Intent.CATEGORY_LAUNCHER);//有图标的就是应用?List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);for (int i=0; i<list.size(); i++) {mAppList.add(list.get(i).loadLabel(pm).toString());}mAdapter.notifyDataSetChanged();}}



AsyncTask是抽象类.AsyncTask定义了三种泛型类型 Params,Progress和Result。
◆Params 启动任务执行的输入参数,比如HTTP请求的URL。
◆Progress 后台任务执行的百分比。
◆Result 后台执行任务最终返回的结果,比如String。
AsyncTask的执行分为四个步骤,每一步都对应一个回调方法,这些方法不应该由应用程序调用,开发者需要做的就是实现这些方法。
onPreExecute(), 该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条。
doInBackground(Params...), 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些很耗时的后台计算工作。可以调用 publishProgress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。
onProgressUpdate(Progress...),在publishProgress方法被调用后,UI thread将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。
onPostExecute(Result), 在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,后台的计算结果将通过该方法传递到UI thread.
为了正确的使用AsyncTask类,以下是几条必须遵守的准则:
1) Task的实例必须在UI thread中创建
2) execute方法必须在UI thread中调用
3) 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法
4) 该task只能被执行一次,否则多次调用时将会出现异常

下面是AsyncTask异步获取已安装程序列表的例子:
public class Screen1 extends Activity{private static final String tag="Screen1";private ListView listview;private Context mContext;private List<ResolveInfo> list;private AppAdapter adapter;private PackageManager pm;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);//给Activity注册界面进度条功能requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);setContentView(R.layout.screen_1);mContext = this;list=new ArrayList<ResolveInfo>();pm = mContext.getPackageManager();listview = (ListView)findViewById(R.id.listview);adapter = new AppAdapter(mContext);listview.setAdapter(adapter);listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {// TODO Auto-generated method stubLog.i(tag, "---------------onItemClick-----------------");ResolveInfo info=list.get(position);String packageName = info.activityInfo.packageName;String className = info.activityInfo.name;Intent intent = new Intent();intent.setClassName(packageName, className);startActivity(intent);}});new MyTask().execute();}class AppAdapter extends BaseAdapter{Context context;AppAdapter(Context context){this.context=context;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn list.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubif(convertView==null){LayoutInflater inflater=getLayoutInflater().from(context);convertView=inflater.inflate(R.layout.simple_item_2, null);}ImageView iv=(ImageView)convertView.findViewById(R.id.icon);TextView tv=(TextView)convertView.findViewById(R.id.text);ResolveInfo info=list.get(position);iv.setBackgroundDrawable(info.activityInfo.loadIcon(pm));tv.setText(info.activityInfo.loadLabel(pm));return convertView;}}class MyTask extends AsyncTask<String, Integer, String>{@Overrideprotected void onPreExecute() {setProgressBarIndeterminateVisibility(true);showProgress();}@Overrideprotected void onPostExecute(String param) {setProgressBarIndeterminateVisibility(false);adapter.notifyDataSetChanged();closeProgress();}@Overrideprotected void onCancelled() {// TODO Auto-generated method stubsuper.onCancelled();}@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);}@Overrideprotected String doInBackground(String... params) {// TODO Auto-generated method stub// 获取已经安装程序列表Intent intent = new Intent(Intent.ACTION_MAIN, null);intent.addCategory(Intent.CATEGORY_LAUNCHER);list = pm.queryIntentActivities(intent, 0);        Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));return null;}}private Dialog dialog;    protected void showProgress() {if(dialog == null) {dialog =  new Dialog(this, R.style.Theme_TransparentDialog);//dialog.setContentView(R.layout.progress_dialog);dialog.setContentView(new ProgressBar(this));dialog.setCancelable(true);dialog.show();}}    //    protected void closeProgress() {if(dialog != null) {dialog.cancel();dialog = null;}}    public boolean isShowing(){    if(dialog != null) {    return dialog.isShowing();    }    return false;    }    }

simple_item_2.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"    >    <TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="应用列表"    />    <ListView  android:id="@+id/listview"    android:layout_width="fill_parent"     android:layout_height="fill_parent"     /></LinearLayout>




Android得到系统已安装应用程序包列表方法 自定义ListView显示 PackageManager的使用

AyncTask 实战 模拟GridView 动态更新效果
http://www.ophonesdn.com/article/show/80
  • 大小: 26.5 KB
  • 大小: 44.1 KB
  • 查看图片附件
0 0
原创粉丝点击