android-如何获取应用程序的程序包名称,然后使用Intent启动该应用程序?

android-如何获取应用程序的程序包名称,然后使用Intent启动该应用程序?,第1张

概述我正在开发一个Android应用程序.在该应用程序中,有一个按钮可以转到另一个活动,其中包含手机上已安装的应用程序的列表.当用户选择一个应用程序时,将保存其程序包名称,并返回上一个活动.但是,如何获得软件包名称?publicclassLoaderCustomSupportextendsSherlockFragmentActivi

我正在开发一个Android应用程序.在该应用程序中,有一个按钮可以转到另一个活动,其中包含手机上已安装的应用程序的列表.当用户选择一个应用程序时,将保存其程序包名称,并返回上一个活动.但是,如何获得软件包名称?

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 onl oadFinished(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 onl oaderreset(Loader<List<AppEntry>> loader) {            // Clear the data in the adapter.            mAdapter.setData(null);        }    }}

解决方法:

这是代码:

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)); }
总结

以上是内存溢出为你收集整理的android-如何获取应用程序的程序包名称,然后使用Intent启动该应用程序?全部内容,希望文章能够帮你解决android-如何获取应用程序的程序包名称,然后使用Intent启动该应用程序?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1095890.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存