Unity3d Android SDK Access Analysis (ii) Unity3d Android SDK design and two access methods

Source: Internet
Author: User

First, preface

The previous article made clear the way unity and Android call, but many of the actual access to the part is not very detailed, because in this article, will detail the specific access to the Android SDK, and how to do a convenient unity Access SDK.

Portal :
Previous: Unity3d and Android call each other
http://blog.csdn.net/yang8456211/article/details/51331358
Post: Unity3d Android SDK Access Analysis (iii) access to the Android library understanding
http://blog.csdn.net/yang8456211/article/details/51435465

Second, Medium: Unity3d Android SDK Design and two access methods (Android SDK access is generally divided into two types)

1) One is to connect the project of unity to the form of Google project
2) Another way to access the Android project by making it into a plugins form

Contrast:

category (Form) Google Project u3d Plugins
Advantages Easy to understand, easy access to native SDK, almost all SDK access Easy access and ease of expansion and management in unity
Disadvantages Access is cumbersome and unfriendly to u3d projects Not all SDKs are available in U3d plugins form
APK Export Android IDE Export Unity Export

Suggestions:

If you do an SDK, it is recommended to separate the Android SDK (can be the library), and the Unity3d form of the SDK (Plugins), because the general project will have their own SDK architecture, and let them break the architecture, export Google Project in the form of access, which is undoubtedly difficult to accept. Let's take a look at the specific operation:
首先我们会自己写一个SDK,并说明白其中的注意点,然后会用两种方式接入这个SDK。
2.1 A simple Android SDK

This SDK implements a few small functions, implementing four methods:

    • Init method, used to pass in the context
    • Pass in two numbers to return their and
    • Incoming MSG, pop up a toast hint
    • Pop up a prompt window, the window needs text information from the strings.xml inside to get, click Confirm Close

First answer a question that may confuse you:

1) When implementing the SDK, must there be a middleware activity inheritance unityplayeractivity?

Almost all the tutorials on the web are taught like this, create a new myactivity, then inherit unityplayeractivity, write the interface in MyActivity, but simply don't tell why.

Some studies on this approach can be seen in the previous article:
http://blog.csdn.net/yang8456211/article/details/51331358.

2) Let's abandon myactivity.

For the question of 1, the answer is no, just to say what I understand is that only when you need to perform some action in the activity's life cycle do we need an intermediate activity to complete these life-cycle related operations, while in other cases a class is sufficient. So let's get started:

    • Create a new Android Project callandroid

    • Remove Mainactivity and Activity_main.xml

    • Create a new Java class name Callmethod and write the above four methods. (You can write it yourself first and then see what's different from what I wrote)

 Public  class callmethod {    Private StaticContext Unitycontext;Private StaticActivity unityactivity;Private StaticAlertdialog.builder alert;//init method used to pass in the context     Public Static void Init(Context Paramcontext)        {unitycontext = Paramcontext.getapplicationcontext ();    Unityactivity = (Activity) paramcontext; }//Pass two numbers back to their and     Public Static int Add(intARG0,intARG1) {returnarg0 + arg1; }//Incoming MSG, pop up a toast hint     Public Static void ShowMessage(FinalString msg) {Unityactivity.runonuithread (NewRunnable () { Public void Run() {Toast.maketext (unitycontext,msg, Toast.length_long). Show ();    }        }); }//Pop up a prompt window, the window needs to get the text information from the Strings.xml inside, click Confirm Close     Public Static void Showalertview() {alert =NewAlertdialog.builder (unityactivity). Settitle ("Pop-up Window"). Setmessage (Unitycontext.getresources (). Getidentifier ("Msgalert","string", Unitycontext.getpackagename ())). Setpositivebutton ("Confirm",NewDialoginterface.onclicklistener () {@Override             Public void OnClick(Dialoginterface arg0,intARG1) {//TODO auto-generated method stubUnityactivity.finish ();        }        }); Unityactivity.runonuithread (NewRunnable () { Public void Run() {alert.show ();    }        }); }}

This small piece of code, the gold content is not small, can solve most of the problems you have encountered ~

1. Do not use activity, what is the activity context?

Using the Init method to get unity to pass in the current context, we get the current activity and application context. (As for Unity's context, I didn't say it clearly, but I did mention it!)-Please keep thinking! )

2. How do I pop up a window? How to operate the interface?

Unity calls the Android method by default not on the UI main thread, so if you want to manipulate the UI interface, use Runonuithread.

3. How can I read the resources of R when I use plugins access?

This problem has plagued me for a long time, because directly put Libs into the plugins will result in not reading the resources, and finally by the anti-compilation of various third-party SDK, only to find the method. This is obtained through the Java Reflection mechanism of unitycontext.getresources (). Getidentifier ("Msgalert", "string", Unitycontext.getpackagename ()). (Here is get a string, analogy other)

4. Can I use static methods only?

Of course not, you can use the instance method, but the static method is more easy to invoke, want to use the instance method, we can create a singleton, and then use this singleton to invoke the instance method.

    privatestaticnull;    publicstaticgetInvokeClass(){        ifnull){            new CallMethod();        }        return invokeSingleTon;    }    publicvoidsayhello(){        //方法内容    }
3) How to publish our SDK?

At this point we have already written our SDK, the SDK is more robust, how to publish the line, you can tick the islibrary in the form of an Android library file to publish, you can also isolate the jar and res, published in Code and resources.

2.2 A simple Unity project

After writing the ANDROIDSDK, we simply wrote a unity project to invoke the Android settings interface.

    • First build an empty unity project named Unitycall
    • Select Camera Maincamera, create a new CS script Calland

    • Bind to main Camera
      Select Main Camera, and in the Add component, select the Calland script you just wrote

The code for the CS script:

Androidjavaclass Unityplayer;    Androidjavaobject currentactivity; Androidjavaclass Androidcall;voidStart () {//Get contextUnityplayer =NewAndroidjavaclass ("Com.unity3d.player.UnityPlayer"); CurrentActivity = unityplayer.getstatic<androidjavaobject> ("CurrentActivity"); Androidcall =NewAndroidjavaclass ("Com.atany.callandroid.CallMethod"); Androidcall.callstatic ("Init", currentactivity); }voidUpdate () {}voidOngui () {GUI.skin.textArea.fontSize = -; GUI.skin.button.fontSize = -;//Add        if(GUI. Button (NewRect ( -, -, the, -),"Add"))          {int sum= androidcall.callstatic<int> ("Add",1,2); Print ("Sum is"+sum); }//ShowMessage        if(GUI. Button (NewRect ( -, -, the, -),"ShowMessage") {androidcall.callstatic ("ShowMessage","Show text for this paragraph"); }//Showalertview        if(GUI. Button (NewRect ( -, the, the, -),"Showalertview") {androidcall.callstatic ("Showalertview"); }    }

Drew three buttons to call our set up Android three different features.

2.3 Export Android Project for access

First of all, let's try exporting the Android project's Access form, export our Unity project, and then access our Android SDK.

    • Export Android Project (shortcut key Shift+ctrl+b bring up build Settings)

    • Import into the IDE use eclipse here, and of course idea is the same.

Note: Be sure to choose existing Android Code into Workspace, don't choose existing projects into Workspace

    • We launched the Android SDK into Jar+res (just a stringnew.xml) and added it to the unity Export project.

-As you can see, we've added two things, a jar and an XML, let's run up and look at the effect

Add:
Click Add to successfully receive the return value for Unity3d printing.

ShowMessage:
Click ShowMessage to successfully display the toast on the current screen.

Showalertview:
Click Showalertview, successfully popup the dialog box in the interface

OK, here I use the export of Google Project to implement the Android SDK access! It also means that the way our resources are read is correct (taking the string resources inside the stringnew), the ability to pop up dialogs and toast implies that you can implement a variety of visual interface operations. Next, let's look at how to access it in the form of a unity plugin.

2.4 Access using the Unity plug-in form

This form is simpler, in short, by putting your resources and jar packages in a form that u3d requires, and then you can run the ~

    • form of building plugins
      We still use the new U3d project, remember that we only added a script at the beginning, and now we are going to build the following structure under assets:

      Plugins:assets 下的根目录(下面可能有Android或者IOS)Android:主目录bin:放中间件的工程(我们没有建立MyActivity的中间件,如果有的话放在这里)libs:放所有jar包res:放所需要的资源
    • Put the Libs and res in our newly exported Android SDK

Note:
1.callAndroid jar is placed in the Libs inside, stringnew This XML is placed in the values inside, I was through the multi-choice to let everyone see I added all the files
2. If there is a middleware myactivity in the bin, or you need to add permissions and Android components, you need to put Androidmanifest into the Android directory.

    • The effect of running and exporting Google project is the same, and I don't have to re-paste it once.
Summarize:

If you're done with me, you should understand the following:
1. Properly complete an SDK that is convenient for unity access
2. Use the Export project mode to complete the SDK access
3. Android Access using the Unity plugin

In the latter part I will talk about specific examples of how to access a specific Android library project.

Third, the demo address Android Access demo is divided into three projects:
    1. Unitycall:plugins form of the Unity3d project
    2. Two projects of Eclipseproj:android
      Unityplayernativeactivity:unity3d Export-Type engineering
      Callandroid:android's SDK Project

http://download.csdn.net/detail/yang8456211/9517718

Yeung Kwong (Atany) Original, reproduced please indicate bloggers and blog links, without the permission of the blogger, prohibit any commercial use.
Post Address: http://download.csdn.net/detail/yang8456211/9517718
Blog Address: http://blog.csdn.net/yang8456211
This article follows "Attribution-non-commercial use-consistent" authoring public agreement

Unity3d Android SDK Access Analysis (ii) Unity3d Android SDK design and two access methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.