App force closes when google+ is not installed

2019-06-17 15:34发布

My requirement is to share on Social networking sites. So, I have already done with Facebook and Twitter. But I am stuck with Google+. I have the following code to share on Google+, but the app forcecloses when I start activity. This occurs only when the Google+ app isn't installed on device already. I know this sharing intent requires the Google+ already installed to start the activity.

Now what I need to do is at least to inform the user that the google+ sharing requires already installed google+ app through dialog or toast instead of getting force closed (If possible by clicking on ok on the dialog should redirect to the google+ on google play). If the google+ app is installed already it goes as usual.

Intent shareIntent = ShareCompat.IntentBuilder.from(this)
             .setText("Hello there! This is a pic of the lazy cat")
             .setType("image/jpeg")
             .setStream(Uri.parse(path))
             .getIntent()
             .setPackage("com.google.android.apps.plus");
 startActivity(shareIntent);

Any help is appreciated. Thanks in advance.

1条回答
倾城 Initia
2楼-- · 2019-06-17 16:26

UPDATE The answer below is outdated. You can now check if the Google+ app is installed through the Google Play Services library (available through the Android SDK). See here for information how to add it to your project.

Example:

int errorCode = GooglePlusUtil.checkGooglePlusApp(mContext);
if (errorCode != GooglePlusUtil.SUCCESS) {
  //Google+ is either not present or another error occured, show the error dialog
  GooglePlusUtil.getErrorDialog(errorCode, this, 0).show();
}
else{
  //Your Google+ related code here
}

OLD ANSWER

You can create some sort of check to see if the Google+ app is installed:

public void loadGooglePlus()
{
    if(isGooglePlusInstalled())
    {
        Intent shareIntent = ShareCompat.IntentBuilder.from(this)
               .setText("Hello there! This is a pic of the lazy cat")
               .setType("image/jpeg")
               .setStream(Uri.parse(path))
               .getIntent()
               .setPackage("com.google.android.apps.plus");
       startActivity(shareIntent);
   }
   else{
      //Notify user
   }
}

public boolean isGooglePlusInstalled()
{
    try
    {
        getPackageManager().getApplicationInfo("com.google.android.apps.plus", 0 );
        return true;
    } 
    catch(PackageManager.NameNotFoundException e)
    {
        return false;
    }
}
查看更多
登录 后发表回答