31

我有一个正在清除缓存的应用程序,但我不知道如何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;
    }
}
4

2 回答 2

62

您应该可以getPackageManager()通过getActivity().

例如getActivity().getPackageManager()

于 2013-09-22T17:10:20.590 回答
2

Kotlin 扩展解决方案

在代码中的某处添加:

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

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

packageManager?.resolveActivity(intent, 0)

// or

fragment.packageManager?.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)
于 2020-05-24T21:22:50.017 回答