Android uses reflection + try catch to realize the method of introducing dependency library on demand in sdk

  • 2021-12-09 10:07:31
  • OfStack

In the process of developing sdk by Android, it is very likely that other three-party sdk libraries will be introduced into sdk. For example, SDK such as Google and Facebook may be included in the development of sdk. But what if the accessor only wants to access SDK with Google login? Can gradle rely only on Google's library and not on Facebook? In this paper, we can simply use Reflection + try catch to realize on-demand access, without creating module and considering the problem of code separation.

Do the following treatment where 3-party sdk is used in your own SDK code:

Original code:


Intent googleSignInIntent = GoogleSignIn.getClient(mLoginActivity, mSignInOption).getSignInIntent();
if (googleSignInIntent != null)
{
  mLoginActivity.startActivityForResult(googleSignInIntent, requestCode);
}

Processed code:


try
{
  Class classGoogleSignIn = Class.forName("com.google.android.gms.auth.api.signin.GoogleSignIn");
  Intent googleSignInIntent = GoogleSignIn.getClient(mLoginActivity, mSignInOption).getSignInIntent();
  if (googleSignInIntent != null)
  {
    mLoginActivity.startActivityForResult(googleSignInIntent, requestCode);
  }
}
catch (Exception e)
{
  e.printStackTrace();
}

That is to say, before using the 3-side sdk code, add the code of class reflection, and then wrap it with try+catch, and the parameter is the complete class name of 3-side sdk (package name + class name)


Class classGoogleSignIn = Class.forName("xxx");

In this way, it is good for the accessor to directly reference the library he wants to access, and the unquoted class error will be received by catch, so as not to flash back, which is simple and convenient ~


Related articles: