如何在Android片段中获取aptPackageManager

时间:2013-09-22 17:07:41

标签: java android

我有这个应用程序,我正在清除缓存,但我无法弄清楚如何让getPackageManager在片段中工作。 这是我的代码。任何帮助将非常感激。我是android和java的新手。非常感谢你。

public class Cache  extends SherlockFragment  {

    Button cache;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.cache, null);
        cache = (Button) view.findViewById(R.id.button3);

        cache.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Cache is Cleared", Toast.LENGTH_SHORT).show();   
                PackageManager  pm = getPackageManager();

                // Get all methods on the PackageManager
                java.lang.reflect.Method[] methods = pm.getClass().getDeclaredMethods();

                for (java.lang.reflect.Method m : methods) {
                    if (m.getName().equals("freeStorageAndNotify")) {
                        // Found the method I want to use
                        try {
                            long desiredFreeStorage = Long.MAX_VALUE; // Request for free space
                            m.invoke(pm, desiredFreeStorage , null);
                        } catch (Exception e) {
                            // Method invocation failed. Could be a permission problem
                        }
                        break;
                    }
                }
            }

            private PackageManager getPackageManager() {
                // TODO Auto-generated method stub
                return null;
            }});
        return view;
    }
}

2 个答案:

答案 0 :(得分:49)

您应该能够通过getPackageManager()访问getActivity()

例如getActivity().getPackageManager()

答案 1 :(得分:2)

Kotlin扩展解决方案

将此添加到您的代码中的某个位置:

val Fragment.packageManager get() = activity?.packageManager

然后直接在您的片段代码中直接使用packageManager

packageManager?.resolveActivity(intent, 0)

// or

fragment.packageManager?.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)