简体   繁体   中英

How to check if a given package is disabled or not and then show toast message accordingly?

I'm making an app where it uses intent to send data to another app. In case, the other app, which is supposed to receive data from my app, is not installed on users's device then it redirects user to play store with toast message asking user to install it. I used "if else" to achieve this. It worked all good until I found that if the other app is disabled by user (OEM installed app which can't be uninstalled), then my app crashes. In such a condition, I want to let user know that the app is disabled by them and ask them to enable it (through toast message). How can I achieve this?

Here is my complete code:

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;
    }


}

I'm not sure if this will work for you, but since you know the package name, you could try this to do a check beforehand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM