【问题标题】:How to check if a given package is disabled or not and then show toast message accordingly?如何检查给定的包是否被禁用,然后相应地显示 toast 消息?
【发布时间】:2025-12-06 22:15:01
【问题描述】:

我正在制作一个应用程序,它使用意图将数据发送到另一个应用程序。万一,应该从我的应用程序接收数据的另一个应用程序未安装在用户的设备上,则它将用户重定向到播放商店,并带有 toast 消息要求用户安装它。我使用“if else”来实现这一点。一切都很好,直到我发现如果其他应用程序被用户禁用(OEM 安装的应用程序无法卸载),那么我的应用程序就会崩溃。在这种情况下,我想让用户知道该应用已被他们禁用并要求他们启用它(通过 toast 消息)。我怎样才能做到这一点?

这是我的完整代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        // Creates button view which is connected to a view in the XML layout, which gets triggered on touching the view.
        TextView textView = (TextView) findViewById(R.id.location);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Use package name which we want to check
                boolean isAppInstalled = appInstalledOrNot("com.google.android.apps.maps");


                if(isAppInstalled){

                    Uri gmmIntentUri = Uri.parse("geo:00,0000,00,0000");
                    Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                    mapIntent.setPackage("com.google.android.apps.maps");
                    startActivity(mapIntent);

                } else {
                    Uri uri2 = Uri.parse("market://details?id=com.google.android.apps.maps");
                    Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri2);
                    Toast.makeText(MainActivity.this, "Google Maps not Installed", Toast.LENGTH_SHORT).show();
                    startActivity(goToMarket);
                }
            }


        });
        
    }

    private boolean appInstalledOrNot(String uri) {
        PackageManager pm = getPackageManager();
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
        }

        return false;
    }


}

【问题讨论】:

    标签: java android android-intent


    【解决方案1】:

    我不确定这是否适合您,但由于您知道包名称,您可以尝试this 事先进行检查。

    【讨论】:

      最近更新 更多