Universal interface development and resource management for Unity access to multiple SDKs (2)

Following the previous article, this article encapsulates the SDK interface. Before you start, you need to understand the following knowledge.

(1) Interaction between unity and android

Unity calls functions in android in the following ways:

method one:

AndroidJavaClass jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject  _mActivity = jc.GetStatic<AndroidJavaObject>("currentActivity");
_mActivity.Call("函数名");

 

Method Two:

AndroidJavaClass jc = new AndroidJavaClass ( " com.unity3d.player.UnityPlayer " ); // The parentheses can be the package name of any jar package + class name 
jc.CallStatic ( " function name " );

 

The first kind of code above first obtains the UnityPlayer class. The UnityPlayer class is the class in unity-classes.jar generated after unity is exported to the Android project. Then get the static variable _mActivity, _mActivity is the type of Activity, thus get the current Activity of Android, and then call the method in this Activity. We can look at the source code in classes.jar automatically generated by unity:

The second is to obtain the class by package name + class name, and directly call the static method in the class. Can be any custom package name and class name. But this has nothing to do with the life cycle of Android.

We can understand in this way that an interface in an Android application is an Activity, and a jump between two interfaces is a jump between two Activities (similar to iOS is a jump between UIController). In fact, our Unity game is also an Android application on Android, so it is also running on an Activity. This Activity is called UnityPlayerActivity, which inherits from Activity. See the source code below. When each Activity is initialized, it will first execute the onCreate () method. So usually the SDK initialization function is also placed in this function. It will be initialized with the Android life cycle. This is the first method and the most commonly used SDK initialization method. There is also a method of SDK initialization, which is to create a new jar package, create a new class in the jar package, write some static methods of SDK initialization in the class, and then call these methods in unity through method two to initialize. We use the method one most people use here, that is, initialize in onCreate ().

With the above understanding, we started the development of unity's common interface. We need an SDKManager class to manage all methods of calling the SDK interface. The code is as follows. Hang the script on an empty object.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class SDKManager : MonoBehaviour {

   private static SDKManager _instance = null;
   public static SDKManager Instance
   {
       get
       {
           return _instance;
       }
   }

   private void Awake()
   {
       if (_instance != null)
       {
           GameObject.Destroy(this.gameObject);
       }
       _instance = this;

       InitSDKManager();

       DontDestroyOnLoad(this);
   }

   private void OnDestroy()
   {
       if (_instance == this) {
           _instance = null;
       }
   }

#if UNITY_ANDROID && !UNITY_EDITOR
   private static string UNITY_CLASS = "com.unity3d.player.UnityPlayer";
   private AndroidJavaObject _mActivity;
#endif
   public void InitSDKManager()
   {
#if UNITY_ANDROID && !UNITY_EDITOR
       AndroidJavaClass jc = new AndroidJavaClass (UNITY_CLASS);
       _mActivity = jc.GetStatic<AndroidJavaObject>("currentActivity");
#endif
   }

   //信鸽SDK接口
   public void GetPushToken()
   {
#if UNITY_ANDROID && !UNITY_EDITOR
       _pushToken = _mActivity.Call<string>("GetXGPushTokenNew");
#endif
   }

   public void SetXGPushTag(string tag)
   {
#if UNITY_ANDROID && !UNITY_EDITOR
       _mActivity.Call("SetXGPushTag",tag);
#endif
   }

   public void AddLocalPushNotificationAndroid(string content, DateTime date, bool isRepeatEveryday = false)
   {
#if UNITY_ANDROID && !UNITY_EDITOR
       int isRepeat = 0;
       if (isRepeatEveryday == true)
       {
           isRepeat = 1;
       }

       _mActivity.Call("AddLocalNotification","SDK集合",content, date.ToString("yyyyMMdd"), date.ToString("HH"), date.ToString("mm"),isRepeat);
#endif
   }

   public void ClearAllLocalNotificationAndroid()
   {
#if UNITY_ANDROID && !UNITY_EDITOR
       _mActivity.Call("ClearAllLocalNotification");
//buglySDK interface
   //
   }#endif

   Start c # exception catch and report function 
   public  void buglyCatch () 
   { 
       Debug.Log ( " start Bugly report " ); 
       BuglyAgent.EnableExceptionHandler (); 

   } 

}

 

Then create a new Test script and hang it on the camera, call these interfaces:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class Test : MonoBehaviour
{

   void OnGUI()
   {
       if (GUILayout.Button("信鸽推送", GUILayout.Width(100.0f), GUILayout.Height(50.0f)))
       {
           DateTime noticeTime = new DateTime(2017, 11, 24, 21, 30, 30);
           SDKManager.Instance.AddLocalPushNotificationAndroid ( " Pushing Pigeon to You " , noticeTime); 
       } 
       if (GUILayout.Button ( " Clear Local Push " , GUILayout.Width ( 100.0f ), GUILayout.Height ( 50.0f ))) 
       { 

           SDKManager. Instance.ClearAllLocalNotificationAndroid (); 
       } 
       if (GUILayout.Button ( " Turn on Bugly exception reporting " , GUILayout.Width ( 100.0f ), GUILayout.Height ( 50.0f ))) 
       { 
           SDKManager.Instance.buglyCatch (); 
       } 
   } 
}}

 

In the above code, we create a new SDKManaget singleton class and encapsulate each SDK interface into a function. For methods in native jar packages like Pigeon, we use _mActivity.Call () to call them. For bugly, which provides an interface, we directly call the provided interface. The general interface class is introduced here. Let's implement the methods in the Android project called in _mActivity.Call (). Create a new project using Android Studio (2.3.3). Our purpose is to make a jar package. This jar package has two functions: (1) It is used to call the methods in the jar package for unity. (2) The life cycle of the Android project exported by Unity. This is why we chose the first access method above. As mentioned above, the Activity that Unity runs is UnityPlayerActivity. We create a new class MainActivity, inheriting com.unity3d.player.UnityPlayerNativeActivity, and UnityPlayerNativeActivity inherits UnityPlayerActivity. Then set MainActivity in AndroidManifest.xml as the activated Activity, so MainActivity is the Activity currently running in Unity. What we get through _mActivity = jc.GetStatic <AndroidJavaObject> ("currentActivity") is MainActivity, and then we implement the function called by unity in MainActivity. Code:

public class MainActivity extends com.unity3d.player.UnityPlayerNativeActivity {

   private static boolean _isXGRegisterSuccess = false;
   private static String _pushToken = "";

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
       if (savedInstanceState == null)
       {
           savedInstanceState = new Bundle();
       }
       super.onCreate(savedInstanceState);
       Log.d("myGame", "MainActivity onCreate Called");

       InitBugly();
       InitXG();
   }

void InitBugly()
{
   CrashReport.initCrashReport(getApplicationContext(),"aaaaaaaa",false);
}

void InitXG(){
   XGPushConfig.enableDebug(this,false);
   MsgReceiver testReceiver = new MsgReceiver();
   IntentFilter intentFilter = new IntentFilter();
   intentFilter.addAction("com.abc.def.receiveintent");
   registerReceiver(testReceiver,intentFilter);
   XGPushManager.registerPush(this, new XGIOperateCallback() {
       @Override
       public void onSuccess(Object o, int i) {
           Log.w("XGPush","XGsuccess:"+o);
           _isXGRegisterSuccess = true;
           _pushToken = o.toString();
       }

       @Override
       public void onFail(Object o, int i, String s) {
           _isXGRegisterSuccess = false;
           Log.w("XGPush","failed:"+i+", msg:"+s);
       }
   });
}

public void AddLocalNotification(String title, String content, String date, String hour, String min, int isRepeatEveryday)
{
   if (_isXGRegisterSuccess)
   {
       XGLocalMessage msg = new XGLocalMessage();
       msg.setTitle(title);
       msg.setContent(content);
       msg.setDate(date);
       msg.setHour(hour);
       msg.setMin(min);

       int notifyIconId = getResources().getIdentifier("notify_icon", "drawable", getPackageName());
       Log.e("notify icon id",notifyIconId+"");
       msg.setSmall_icon(Integer.toString(notifyIconId));

       int _hour = Integer.parseInt(hour);
       int _min = Integer.parseInt(min);
       msg.setRing(1);

       XGPushManager.addLocalNotification(MainActivity.this,msg);
   }
}
public void ClearAllLocalNotification()
{
   Log.w("ClearAllLocalNotice","success");
   if (_isXGRegisterSuccess)
   {
       XGPushManager.clearLocalNotifications(MainActivity.this);
   }
}
}

 

If you need to do some processing before starting the Activity (that is, MainActivity) of Unity, you can create a new class SplashActivity to inherit Activity, set SplashActivity to start Activity, and then jump to MainActivity. You can do some pre-game processing in SplashActivity. After we have done the above work, we can package these classes into a jar package (how to AS jar package, let's import), and import it into the Android project exported by unity. At this point, the development of the universal interface is over. The only remaining work is the SDK resources that we extracted from Unity before. We need to add them to the Android project. The following describes how to perform resource management and add resources to the Android project exported by Unity.

Note:

AS jar package, add these codes at the end of build.gradle:

task makeJar (type: Jar, dependsOn: ['build' ]) { 
   archiveName = 'QuicksdkDemo.jar'      // package name 
   from ('build / intermediates / classes / debug /' ) 
   destinationDir = file ('build / libs')      // Export path 
   exclude ('com / taiyouxi / a3k / BuildConfig.class')      // File not included in the package 
   exclude ('com / taiyouxi / a3k / BuildConfig \ $ *. Class')      // Do not enter the package File 
   exclude ('** / R.class')      // files not included in the package 
   exclude (' ** / R \ $ *. Class')      // files not included in the package 
   include ('com / taiyouxi / a3k /*.class'     ) // The files that need to be included in the package 
   include ('com / quicksdk / unity / *. Class')     // The files to be included in the package 
   include ('com / weibo / *. Class')      // The files to be included in the package 
   include ('com / wxapi / *. Class')      // The files to be included in the package 
) 
makeJar .dependsOn (build)

 

Then open the Terminal window, type gradlew makeJar and press Enter:

gradlew makeJar

The generated package is shown in the build> libs folder:

Guess you like

Origin www.cnblogs.com/gangtie/p/12731891.html