如何获取应用程序的包名,然后使用意向推出该应用程序? [英] How to get the package name of an application and then launch that app using Intent?

查看:413
本文介绍了如何获取应用程序的包名,然后使用意向推出该应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个Android应用程序。在该应用程序,有一个按钮转到包含安装在手机上的应用程序的列表,另一个活动。当用户选择一个应用程序,它的包名被保存,并且用户返回到previous活动。但是,我怎么能得到包的名称?

 公共类LoaderCustomSupport扩展SherlockFragmentActivity {

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        FragmentManager FM = getSupportFragmentManager();

        //创建列表片段并将其添加为我们唯一的内容。
        如果(fm.findFragmentById(android.R.id.content)== NULL){
            AppListFragment名单=新AppListFragment();
            。fm.beginTransaction()加(android.R.id.content,列表).commit();
        }
    }

    / **
     *此类包含在我们的装载机在每个项目的数据。
     * /
    公共静态类AppEntry {
        公共AppEntry(AppListLoader装载机,ApplicationInfo资讯){
            mLoader =装载机;
            明复=信息;
            mApkFile =新的文件(info.sourceDir);
        }

        公共ApplicationInfo getApplicationInfo(){
            返回明复;
        }

        公共字符串getLabel(){
            返回mLabel;
        }

        公众可绘制调用getIcon(){
            如果(米康== NULL){
                如果(mApkFile.exists()){
                    米康= mInfo.loadIcon(mLoader.mPm);
                    返回米康;
                } 其他 {
                    mMounted = FALSE;
                }
            }否则,如果(!mMounted){
                //如果未安装应用程序,但现在安装,重装
                //它的图标。
                如果(mApkFile.exists()){
                    mMounted = TRUE;
                    米康= mInfo.loadIcon(mLoader.mPm);
                    返回米康;
                }
            } 其他 {
                返回米康;
            }

            返回mLoader.getContext()。getResources()。getDrawable(
                android.R.drawable.sym_def_app_icon);
        }

        @覆盖
        公共字符串的toString(){
            返回mLabel;
        }

        无效loadLabel(上下文的背景下){
            如果(mLabel == NULL ||!mMounted){
                如果(!mApkFile.exists()){
                    mMounted = FALSE;
                    mLabel = mInfo.packageName;
                } 其他 {
                    mMounted = TRUE;
                    CharSequence的标签= mInfo.loadLabel(context.getPackageManager());
                    mLabel =标签!= NULL? label.toString():mInfo.packageName;
                }
            }
        }

        私人最终AppListLoader mLoader;
        私人最终ApplicationInfo明复;
        私人最终文件mApkFile;
        私人字符串mLabel;
        私人绘制对象米康;
        私人布尔mMounted;
    }

    / **
     *执行应用程序入口的对象按字母顺序排列的比较。
     * /
    公共静态最终比较< AppEntry> ALPHA_COMPARATOR =新的比较< AppEntry>(){
        私人最终分页器sCollat​​or = Collat​​or.getInstance();

        @覆盖
        公众诠释比较(AppEntry object1,AppEntry Object2的){
            返回sCollat​​or.compare(object1.getLabel(),object2.getLabel());
        }
    };

    / **
     *辅助,用于确定如果配置在一个有趣的已改变
     *方式,所以我们需要重新构建应用程序列表。
     * /
    公共静态类InterestingConfigChanges {
        最终的配置mLastConfiguration =新配置();
        INT mLastDensity;

        布尔applyNewConfig(资源RES){
            INT configChanges = mLastConfiguration.updateFrom(res.getConfiguration());
            布尔densityChanged = mLastDensity = res.getDisplayMetrics()densityDpi!。
            如果(densityChanged ||(configChanges及(ActivityInfo.CONFIG_LOCALE
                    | ActivityInfoCompat.CONFIG_UI_MODE | ActivityInfo.CONFIG_SCREEN_LAYOUT))= 0){!
                mLastDensity = res.getDisplayMetrics()densityDpi。
                返回true;
            }
            返回false;
        }
    }

    / **
     * Helper类来寻找有趣的变化对安装的应用程序
     *以使装载机可以更新。
     * /
    公共静态类PackageIntentReceiver扩展的BroadcastReceiver {
        最后AppListLoader mLoader;

        公共PackageIntentReceiver(AppListLoader装载机){
            mLoader =装载机;
            IntentFilter的过滤器=新的IntentFilter(Intent.ACTION_PACKAGE_ADDED);
            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
            filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
            filter.addDataScheme(包);
            。mLoader.getContext()registerReceiver(这一点,过滤器);
            //注册有关SD卡的安装活动。
            IntentFilter的sdFilter =新的IntentFilter();
            sdFilter.addAction(IntentCompat.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
            sdFilter.addAction(IntentCompat.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
            。mLoader.getContext()registerReceiver(这一点,sdFilter);
        }

        @覆盖
        公共无效的onReceive(上下文的背景下,意图意图){
            //告诉关于变更装载机。
            mLoader.onContentChanged();
        }
    }

    / **
     *自定义加载器加载所有已安装的应用程序。
     * /
    公共静态类AppListLoader扩展AsyncTaskLoader<列表< AppEntry>> {
        最后InterestingConfigChanges mLastConfig =新InterestingConfigChanges();
        最后PackageManager MPM;

        名单< AppEntry> MAPPS;
        PackageIntentReceiver mPackageObserver;

        公共AppListLoader(上下文的背景下){
            超(上下文);

            //为以后使用包管理器;注意:我们不
            //使用语境直接,而是保存全球应用
            //通过的getContext返回的上下文()。
            MPM =的getContext()getPackageManager()。
        }

        / **
         *这是在散装我们的工作就完成了。此功能是
         *调用后台线程,应该生成一组新的
         *数据由装载器被公开。
         * /
        @覆盖
        公开名单< AppEntry> loadInBackground(){
            //获得所有已知的应用程序。
            名单< ApplicationInfo>应用程序= mPm.getInstalledApplications(
                PackageManager.GET_UNINSTALLED_PACKAGES |
                PackageManager.GET_DISABLED_COMPONENTS);
            如果(应用程序== NULL){
                应用程序=新的ArrayList< ApplicationInfo>();
            }

            最终的上下文语境=的getContext();

            //创建条目相应的数组并加载它们的标签。
            名单< AppEntry>项=新的ArrayList< AppEntry>(apps.size());
            的for(int i = 0; I< apps.size();我++){
                AppEntry进入=新AppEntry(这一点,apps.get(I));
                entry.loadLabel(上下文);
                entries.add(入口);
            }

            //排序列表。
            Collections.sort(条目,ALPHA_COMPARATOR);

            //完成!
            返回条目;
        }

        / **
         *当有新的数据提供给客户端调用。该
         *超类将提供它的服务;实施
         *这里只是增加了一些逻辑。
         * /
        @覆盖
        公共无效deliverResult(名单< AppEntry>应用程序){
            如果(isReset()){
                //异步查询进来,而装载机停止。我们
                //不需要的结果。
                如果(应用程序!= NULL){
                    onReleaseResources(应用程序);
                }
            }
            名单< AppEntry> oldApps =应用程序;
            MAPPS =应用程序;

            如果(isStarted()){
                //如果加载器目前开始,我们马上就可以
                //提供其结果。
                super.deliverResult(应用程序);
            }

            //在这一点上,我们可以释放与之关联的资源
            //'oldApps如果需要的话;现在,新的结果提供了我们
            //知道这是不再使用。
            如果(oldApps!= NULL){
                onReleaseResources(oldApps);
            }
        }

        / **
         *处理的请求启动加载器。
         * /
        @覆盖
        保护无效onStartLoading(){
            如果(MAPPS!= NULL){
                //如果我们现在有一个可用的结果,提供它
                // 立即。
                deliverResult(MAPPS);
            }

            //开始窥伺变化的应用程序数据。
            如果(mPackageObserver == NULL){
                mPackageObserver =新PackageIntentReceiver(本);
            }

            //先后在配置一些有趣的事情,因为我们改变
            //最后建成的应用程序列表?
            布尔configChange = mLastConfig.applyNewConfig(的getContext()getResources());

            如果(takeContentChanged()|| MAPPS == NULL || configChange){
                //如果自上次的数据已经改变它是装
                //或者当前不可用,启动负载。
                的forceload();
            }
       }

        / **
         *处理的请求停止加载程序。
         * /
        @覆盖
        保护无效onStopLoading(){
            //尝试如果可能的话,取消当前的负载任务。
            cancelLoad();
        }

        / **
         *处理的请求取消负载。
         * /
        @覆盖
        公共无效onCanceled(名单< AppEntry>应用程序){
            super.onCanceled(应用程序);

            //在这一点上,我们可以释放与应用程序相关的资源
            // 如果需要的话。
            onReleaseResources(应用程序);
        }

        / **
         *处理的请求完全复位的装载机。
         * /
        @覆盖
        保护无效onReset(){
            super.onReset();

            //确保装载机被停止
            onStopLoading();

            //在这一点上,我们可以释放与应用程序相关的资源
            // 如果需要的话。
            如果(MAPPS!= NULL){
                onReleaseResources(MAPPS);
                MAPPS = NULL;
            }

            //更改停止监视。
            如果(mPackageObserver!= NULL){
                。的getContext()unregisterReceiver(mPackageObserver);
                mPackageObserver = NULL;
            }
        }

        / **
         *辅助功能,充分利用相关资源的释放护理
         *与积极加载的数据集。
         * /
        保护无效onReleaseResources(名单< AppEntry>应用程序){
            //对于一个简单的名单,其中;>没有什么可以做的。对于一些
            //就像一个光标,我们会在这里关闭它。
        }
    }

    公共静态类AppListAdapter扩展ArrayAdapter< AppEntry> {
        私人最终LayoutInflater mInflater;

        公共AppListAdapter(上下文的背景下){
            超(背景下,android.R.layout.simple_list_item_2);
            mInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        公共无效使用setData(名单< AppEntry>数据){
            明确();
            如果(数据!= NULL){
                对于(AppEntry appEntry:数据){
                    加(appEntry);
                }
            }
        }

        / **
         *填充在列表中新的项目。
         * /
        @覆盖
        公共查看getView(INT位置,查看convertView,ViewGroup中父){
            查看图。

            如果(convertView == NULL){
                鉴于= mInflater.inflate(R.layout.list_item_icon_text,父母,假);
            } 其他 {
                鉴于= convertView;
            }

            AppEntry项目=的getItem(位置);
            ((ImageView的)view.findViewById(R.id.icon))setImageDrawable(item.getIcon());
            ((TextView的)view.findViewById(R.id.text))的setText(item.getLabel());

            返回查看;
        }
    }

    公共静态类AppListFragment扩展SherlockListFragment
            实现LoaderManager.LoaderCallbacks<列表< AppEntry>> {

        //这是适配器被用于显示该列表的数据。
        AppListAdapter mAdapter;

        //如果非空,这是当前过滤器的用户提供。
        字符串mCurFilter;

        OnQueryTextListenerCompat mOnQueryTextListenerCompat;

        @覆盖
        公共无效onActivityCreated(包savedInstanceState){
            super.onActivityCreated(savedInstanceState);

            //给一些文本,以显示是否有任何数据。在一个实
            //应用程序,这将来自资源。
            setEmptyText(无应用程序);

            //我们有一个菜单项,在操作栏中显示。
            setHasOptionsMenu(真正的);

            //创建一个空的适配器,我们将用它来显示加载的数据。
            mAdapter =新AppListAdapter(getActivity());
            setListAdapter(mAdapter);

            //开始一个进度指示器。
            setListShown(假);

            // prepare装载机。无论是与现有的一个重新连接,
            //或者开始一个新的。
            getLoaderManager()initLoader(0,空,这一点)。
        }

        @覆盖
        公共无效onCreateOptionsMenu(功能菜单,MenuInflater充气){
            //放置一个动作栏项目的进行搜索。
            菜单项项= menu.add(搜索);
            item.setIcon(android.R.drawable.ic_menu_search);
            item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            视图搜索查看= SearchViewCompat.newSearchView(getActivity());
            如果(搜索查看!= NULL){
                SearchViewCompat.setOnQueryTextListener(搜索查看,
                        新OnQueryTextListenerCompat(){
                    @覆盖
                    公共布尔onQueryTextChange(字符串newText){
                        //调用时的动作栏搜索文本已更改。由于这
                        //是一个简单的数组适配器,我们就可以把它做过滤。
                        mCurFilter =!TextUtils.isEmpty(newText)? newText:空;
                        。mAdapter.getFilter()过滤器(mCurFilter);
                        返回true;
                    }
                });
                item.setActionView(搜索查看);
            }
        }

        @覆盖
        公共无效onListItemClick(ListView的L,视图V,INT位置,长的id){
            //插入所需的行为在这里。
            Log.i(LoaderCustom,项目点:+ ID);
           //在这里,我想知道在列表中选择应用程序项目的包名
        }

        @覆盖
        公共装载机<列表< AppEntry>> onCreateLoader(INT ID,捆绑参数){
            //一个新的Loader需要创建时,这就是所谓的。本
            //样品只有一个加载器不带任何参数,所以很简单。
            返回新AppListLoader(getActivity());
        }

        @覆盖
        公共无效onLoadFinished(装载机<列表< AppEntry>>装载机,名单,其中,AppEntry>数据){
            //设置适配器中的新数据。
            mAdapter.setData(数据);

            //现在应该显示的列表。
            如果(isResumed()){
                setListShown(真正的);
            } 其他 {
                setListShownNoAnimation(真正的);
            }
        }

        @覆盖
        公共无效onLoaderReset(装载机<列表< AppEntry>>装载机){
            //清除在适配器中的数据。
            mAdapter.setData(空);
        }
    }
}
 

解决方案

下面是code:

 最后PackageManager PM = getPackageManager();
//获取安装的应用程序列表。
名单< ApplicationInfo>包= pm.getInstalledApplications(PackageManager.GET_META_DATA);

对于(ApplicationInfo packageInfo:包){
    Log.d(TAG,安装包:+ packageInfo.packageName);
    Log.d(TAG,启动活动:+ pm.getLaunchIntentForPackage(packageInfo.packageName));
}
 

I am developing an Android app. In that app, there is a button to go to another activity which contains a list of installed apps on the phone. When the user selects an app, its package name is saved and the user returns to the previous activity. But, how can I get the package name?

public class LoaderCustomSupport extends SherlockFragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FragmentManager fm = getSupportFragmentManager();

        // Create the list fragment and add it as our sole content.
        if (fm.findFragmentById(android.R.id.content) == null) {
            AppListFragment list = new AppListFragment();
            fm.beginTransaction().add(android.R.id.content, list).commit();
        }
    }

    /**
     * This class holds the per-item data in our Loader.
     */
    public static class AppEntry {
        public AppEntry(AppListLoader loader, ApplicationInfo info) {
            mLoader = loader;
            mInfo = info;
            mApkFile = new File(info.sourceDir);
        }

        public ApplicationInfo getApplicationInfo() {
            return mInfo;
        }

        public String getLabel() {
            return mLabel;
        }

        public Drawable getIcon() {
            if (mIcon == null) {
                if (mApkFile.exists()) {
                    mIcon = mInfo.loadIcon(mLoader.mPm);
                    return mIcon;
                } else {
                    mMounted = false;
                }
            } else if (!mMounted) {
                // If the app wasn't mounted but is now mounted, reload
                // its icon.
                if (mApkFile.exists()) {
                    mMounted = true;
                    mIcon = mInfo.loadIcon(mLoader.mPm);
                    return mIcon;
                }
            } else {
                return mIcon;
            }

            return mLoader.getContext().getResources().getDrawable(
                android.R.drawable.sym_def_app_icon);
        }

        @Override
        public String toString() {
            return mLabel;
        }

        void loadLabel(Context context) {
            if (mLabel == null || !mMounted) {
                if (!mApkFile.exists()) {
                    mMounted = false;
                    mLabel = mInfo.packageName;
                } else {
                    mMounted = true;
                    CharSequence label = mInfo.loadLabel(context.getPackageManager());
                    mLabel = label != null ? label.toString() : mInfo.packageName;
                }
            }
        }

        private final AppListLoader mLoader;
        private final ApplicationInfo mInfo;
        private final File mApkFile;
        private String mLabel;
        private Drawable mIcon;
        private boolean mMounted;
    }

    /**
     * Perform alphabetical comparison of application entry objects.
     */
    public static final Comparator<AppEntry> ALPHA_COMPARATOR = new Comparator<AppEntry>() {
        private final Collator sCollator = Collator.getInstance();

        @Override
        public int compare(AppEntry object1, AppEntry object2) {
            return sCollator.compare(object1.getLabel(), object2.getLabel());
        }
    };

    /**
     * Helper for determining if the configuration has changed in an interesting
     * way so we need to rebuild the app list.
     */
    public static class InterestingConfigChanges {
        final Configuration mLastConfiguration = new Configuration();
        int mLastDensity;

        boolean applyNewConfig(Resources res) {
            int configChanges = mLastConfiguration.updateFrom(res.getConfiguration());
            boolean densityChanged = mLastDensity != res.getDisplayMetrics().densityDpi;
            if (densityChanged || (configChanges&(ActivityInfo.CONFIG_LOCALE
                    |ActivityInfoCompat.CONFIG_UI_MODE|ActivityInfo.CONFIG_SCREEN_LAYOUT)) != 0) {
                mLastDensity = res.getDisplayMetrics().densityDpi;
                return true;
            }
            return false;
        }
    }

    /**
     * Helper class to look for interesting changes to the installed apps
     * so that the loader can be updated.
     */
    public static class PackageIntentReceiver extends BroadcastReceiver {
        final AppListLoader mLoader;

        public PackageIntentReceiver(AppListLoader loader) {
            mLoader = loader;
            IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
            filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
            filter.addDataScheme("package");
            mLoader.getContext().registerReceiver(this, filter);
            // Register for events related to sdcard installation.
            IntentFilter sdFilter = new IntentFilter();
            sdFilter.addAction(IntentCompat.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
            sdFilter.addAction(IntentCompat.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
            mLoader.getContext().registerReceiver(this, sdFilter);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            // Tell the loader about the change.
            mLoader.onContentChanged();
        }
    }

    /**
     * A custom Loader that loads all of the installed applications.
     */
    public static class AppListLoader extends AsyncTaskLoader<List<AppEntry>> {
        final InterestingConfigChanges mLastConfig = new InterestingConfigChanges();
        final PackageManager mPm;

        List<AppEntry> mApps;
        PackageIntentReceiver mPackageObserver;

        public AppListLoader(Context context) {
            super(context);

            // Retrieve the package manager for later use; note we don't
            // use 'context' directly but instead the save global application
            // context returned by getContext().
            mPm = getContext().getPackageManager();
        }

        /**
         * This is where the bulk of our work is done.  This function is
         * called in a background thread and should generate a new set of
         * data to be published by the loader.
         */
        @Override
        public List<AppEntry> loadInBackground() {
            // Retrieve all known applications.
            List<ApplicationInfo> apps = mPm.getInstalledApplications(
                PackageManager.GET_UNINSTALLED_PACKAGES |
                PackageManager.GET_DISABLED_COMPONENTS);
            if (apps == null) {
                apps = new ArrayList<ApplicationInfo>();
            }

            final Context context = getContext();

            // Create corresponding array of entries and load their labels.
            List<AppEntry> entries = new ArrayList<AppEntry>(apps.size());
            for (int i=0; i<apps.size(); i++) {
                AppEntry entry = new AppEntry(this, apps.get(i));
                entry.loadLabel(context);
                entries.add(entry);
            }

            // Sort the list.
            Collections.sort(entries, ALPHA_COMPARATOR);

            // Done!
            return entries;
        }

        /**
         * Called when there is new data to deliver to the client.  The
         * super class will take care of delivering it; the implementation
         * here just adds a little more logic.
         */
        @Override
        public void deliverResult(List<AppEntry> apps) {
            if (isReset()) {
                // An async query came in while the loader is stopped.  We
                // don't need the result.
                if (apps != null) {
                    onReleaseResources(apps);
                }
            }
            List<AppEntry> oldApps = apps;
            mApps = apps;

            if (isStarted()) {
                // If the Loader is currently started, we can immediately
                // deliver its results.
                super.deliverResult(apps);
            }

            // At this point we can release the resources associated with
            // 'oldApps' if needed; now that the new result is delivered we
            // know that it is no longer in use.
            if (oldApps != null) {
                onReleaseResources(oldApps);
            }
        }

        /**
         * Handles a request to start the Loader.
         */
        @Override
        protected void onStartLoading() {
            if (mApps != null) {
                // If we currently have a result available, deliver it
                // immediately.
                deliverResult(mApps);
            }

            // Start watching for changes in the app data.
            if (mPackageObserver == null) {
                mPackageObserver = new PackageIntentReceiver(this);
            }

            // Has something interesting in the configuration changed since we
            // last built the app list?
            boolean configChange = mLastConfig.applyNewConfig(getContext().getResources());

            if (takeContentChanged() || mApps == null || configChange) {
                // If the data has changed since the last time it was loaded
                // or is not currently available, start a load.
                forceLoad();
            }
       }

        /**
         * Handles a request to stop the Loader.
         */
        @Override
        protected void onStopLoading() {
            // Attempt to cancel the current load task if possible.
            cancelLoad();
        }

        /**
         * Handles a request to cancel a load.
         */
        @Override
        public void onCanceled(List<AppEntry> apps) {
            super.onCanceled(apps);

            // At this point we can release the resources associated with 'apps'
            // if needed.
            onReleaseResources(apps);
        }

        /**
         * Handles a request to completely reset the Loader.
         */
        @Override
        protected void onReset() {
            super.onReset();

            // Ensure the loader is stopped
            onStopLoading();

            // At this point we can release the resources associated with 'apps'
            // if needed.
            if (mApps != null) {
                onReleaseResources(mApps);
                mApps = null;
            }

            // Stop monitoring for changes.
            if (mPackageObserver != null) {
                getContext().unregisterReceiver(mPackageObserver);
                mPackageObserver = null;
            }
        }

        /**
         * Helper function to take care of releasing resources associated
         * with an actively loaded data set.
         */
        protected void onReleaseResources(List<AppEntry> apps) {
            // For a simple List<> there is nothing to do.  For something
            // like a Cursor, we would close it here.
        }
    }

    public static class AppListAdapter extends ArrayAdapter<AppEntry> {
        private final LayoutInflater mInflater;

        public AppListAdapter(Context context) {
            super(context, android.R.layout.simple_list_item_2);
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void setData(List<AppEntry> data) {
            clear();
            if (data != null) {
                for (AppEntry appEntry : data) {
                    add(appEntry);
                }
            }
        }

        /**
         * Populate new items in the list.
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;

            if (convertView == null) {
                view = mInflater.inflate(R.layout.list_item_icon_text, parent, false);
            } else {
                view = convertView;
            }

            AppEntry item = getItem(position);
            ((ImageView)view.findViewById(R.id.icon)).setImageDrawable(item.getIcon());
            ((TextView)view.findViewById(R.id.text)).setText(item.getLabel());

            return view;
        }
    }

    public static class AppListFragment extends SherlockListFragment
            implements LoaderManager.LoaderCallbacks<List<AppEntry>> {

        // This is the Adapter being used to display the list's data.
        AppListAdapter mAdapter;

        // If non-null, this is the current filter the user has provided.
        String mCurFilter;

        OnQueryTextListenerCompat mOnQueryTextListenerCompat;

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            // Give some text to display if there is no data.  In a real
            // application this would come from a resource.
            setEmptyText("No applications");

            // We have a menu item to show in action bar.
            setHasOptionsMenu(true);

            // Create an empty adapter we will use to display the loaded data.
            mAdapter = new AppListAdapter(getActivity());
            setListAdapter(mAdapter);

            // Start out with a progress indicator.
            setListShown(false);

            // Prepare the loader.  Either re-connect with an existing one,
            // or start a new one.
            getLoaderManager().initLoader(0, null, this);
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            // Place an action bar item for searching.
            MenuItem item = menu.add("Search");
            item.setIcon(android.R.drawable.ic_menu_search);
            item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            View searchView = SearchViewCompat.newSearchView(getActivity());
            if (searchView != null) {
                SearchViewCompat.setOnQueryTextListener(searchView,
                        new OnQueryTextListenerCompat() {
                    @Override
                    public boolean onQueryTextChange(String newText) {
                        // Called when the action bar search text has changed.  Since this
                        // is a simple array adapter, we can just have it do the filtering.
                        mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
                        mAdapter.getFilter().filter(mCurFilter);
                        return true;
                    }
                });
                item.setActionView(searchView);
            }
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            // Insert desired behavior here.
            Log.i("LoaderCustom", "Item clicked: " + id);
           //Here i want to know the package name of the selected app item in the list
        }

        @Override
        public Loader<List<AppEntry>> onCreateLoader(int id, Bundle args) {
            // This is called when a new Loader needs to be created.  This
            // sample only has one Loader with no arguments, so it is simple.
            return new AppListLoader(getActivity());
        }

        @Override
        public void onLoadFinished(Loader<List<AppEntry>> loader, List<AppEntry> data) {
            // Set the new data in the adapter.
            mAdapter.setData(data);

            // The list should now be shown.
            if (isResumed()) {
                setListShown(true);
            } else {
                setListShownNoAnimation(true);
            }
        }

        @Override
        public void onLoaderReset(Loader<List<AppEntry>> loader) {
            // Clear the data in the adapter.
            mAdapter.setData(null);
        }
    }
}

解决方案

Here is the code:

final PackageManager pm = getPackageManager();
//get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo packageInfo : packages) {
    Log.d(TAG, "Installed package :" + packageInfo.packageName);
    Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName)); 
}

这篇关于如何获取应用程序的包名,然后使用意向推出该应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆