Android packs activity and other classes into jar packages for third-party calls

Source: Internet
Author: User


In the development of Java Engineering, a project may be divided into several modules, in order to achieve decoupling and independence between the modules, improve the reuse of modules, usually the project is divided into several Java projects according to the module development, and finally through the jar package and other projects rely on the way to achieve system integration, improve the coupling and reuse of modules.

Now the development of Android projects through practice and summary, found that this method is particularly necessary, such as the development of a video playback function of the Android, there must be a play and download modules, if not separate in a project to constantly add new features, the product of each research and development are constantly adding modification function, The final maintenance is getting harder, bugs are getting more and more, and it's a bit of a way to avoid this situation. Second, the download module is a lot of apps will be used by the module, independent of the continuous improvement and optimization, can become a component to different applications, which improves the module's code decoupling, improve the reusability, improve the efficiency, benefits greatly oh.

Due to the peculiarities of Android, Android has not only Java files and res files, but also the need to study how to package resource files and activity files into jar files for other projects to invoke, and eventually try to find the following two solutions.

Programme one:

Based on the official Android documentation, set one of the items as a reference library and add a reference to the library in another project.

The simple approach is

Add a row to project.properties in the referenced project Testjar

Android.library=true

Added in Project.Properties of referenced project Testmain

Android.library=false android.library.reference.1=. /testjar

Where 1 indicates the ordinal of the reference package, ". /testjar "indicates the path of the referenced project

Here's how to do this in eclipse:

    1. Set up normal Android project as a library item
      Library project is also a standard Android project, so you first create a normal Android project, this project can be any name, any package name, set other need to set the field and so on.
      Then set up the project as a library project, with the following steps:
      1) in the Package Explorer, right-click the project folder (Testjar) and tap properties.
      2) in the Properties window, select "Android" and the library properties are displayed on the bottom right.
      3) Select the "Is Library" Radio box and click Apply.
      4) Click OK to close the properties.
      At this point, the project becomes a library project, of course, the Pure Java project can also become a library project, very simple, the implementation of the above four steps is OK. Other program projects can reference this library project.


Referencing library Items
If you are developing an application that wants to invoke code and resources in a library project, it is also easy to refer to the following steps:
1) In the Package Explorer, right-click the project folder (Testjar) and tap properties.
2) In the Properties window, select "Android" and the library properties are displayed on the bottom right.
3) Click Add to open the Project selection dialog box.
4) Select the library item to add from the list of available library items and click OK.
5) Click Apply when the dialog box is closed (in the Properties window).
6) Click OK to close the Properties window.
By completing the six steps above, Eclipse will rebuild the project and include the inside of the Library project.



    1. If you want to add references to multiple library projects, use up and down to set their relative precedence and merge order. When the tool merges the referenced libraries, the order is from the lower priority (below the list) to the high priority (above the list). If more than one library defines the same resource ID, the tool chooses a resource with a high priority. The application itself has the highest priority.

Scenario Two:

By exporting the jar package to other projects to refer to, no resource package is not much to say the direct export jar package can be directly referenced, the following is said when there is a resource package exists when the package jar and reference method.

Implementation steps:

    1. We're building a new engineering Testjar, and this is what we're going to pack into a jar project.

  1. Note: Mresource This class is important, mainly its role, using reflection to obtain the resource ID according to the resource name (in fact, the system also comes with the method of obtaining resource ID according to the resource name Getresources (). Getidentifier ("main_activity "Layout", Getpackagename ()); The first parameter is the name of the resource, the second parameter is the type of the resource, such as layout, string, etc., and the third is the package name)

  2. The Mrsource.java code is as follows:
    Import android.content.context;/** * gets its ID value based on the name of the resource * * @author Yangzy */public class Mresource {public static int get        Idbyname (context context, string ClassName, String name) {String packagename = Context.getpackagename ();        Class r = null;        int id = 0; try {r = class.forname (PackageName + ").            R ");            class[] classes = r.getclasses ();            Class desireclass = null;                     for (int i = 0; i < classes.length; ++i) {if (Classes[i].getname (). Split ("\\$") [1].equals (ClassName)) {                    Desireclass = Classes[i];                Break        }} if (Desireclass! = null) id = Desireclass.getfield (name). GETINT (Desireclass);        } catch (ClassNotFoundException e) {e.printstacktrace ();        } catch (IllegalArgumentException e) {e.printstacktrace ();        } catch (SecurityException e) {e.printstacktrace (); } catch (Illegalaccessexception e)        {E.printstacktrace ();        } catch (Nosuchfieldexception e) {e.printstacktrace ();    } return ID; }}
  3. Import Android.content.context;public class Statistics {public static Statistics mstatistics;public static Context Mcontext;public static Statistics getinstance () {if (mstatistics = = null) {mstatistics = new Statistics ();} return mstatistics;} public void init (context context) {This.mcontext = context; System.out.println ("--statistics---init--");} public void Login (int num) {System.out.println ("--statistics---" + num);}}


  4. Testutiljar.java implementation comparison simple a picture clicked and popped a toast
    Import Android.app.activity;import android.content.context;import android.os.bundle;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.imageview;import Android.widget.toast;public class    Testutiljar extends Activity {private ImageView ImageView;    Private context context;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (Mresource.getidbyname (Getapplication (), "Layout", "Jar_activity_main"));        context = this;        ImageView = (ImageView) Findviewbyid (Mresource.getidbyname (Getapplication (), "id", "Jar_imageview"));                Imageview.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {                        TODO auto-generated Method Stub toast.maketext (context,     "jar =" + getapplication (). GetString (                                   Mresource.getidbyname (Getapplication (), "string",            "Jar_test_name")), Toast.length_short). Show ();    }        }); }}


  5. The layout file is as follows:
    <relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:backg Round= "#00eeff" tools:context= ".        Mainactivity "> <imageview android:id=" @+id/jar_imageview "android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:layout_centerinparent= "true" android:layout_marginbottom= "80 DP "android:src=" @drawable/photo "/></relativelayout>
  6. Export Testjar as Jar package, go out all resources file, export only source code

6. Import the exported Testjar1.jar into the project to be referenced, and copy to Libs below

The most critical step is to copy all the resource files referenced in the Testjar to Testmain so that you can refer to the resource files successfully. There is also an activity that needs to be testmain androidmanifest.xml to configure the corresponding package name to use the activity in the jar package.



  1. Referencing in Testmain
    Package Com.example.testmain;import Com.example.testjar.testutiljar;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.view.view;import Android.view.View.OnClickListener Import Android.widget.button;public class Mainactivity extends Activity implements Onclicklistener {private Button bu    Tton;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Button = (button) Findviewbyid (R.id.button1); Button.setonclicklistener (this); Statistics.getinstance (). Init (this); Statistics.getinstance ().    Login (19911019);            } @Override public void OnClick (View v) {//TODO auto-generated Method Stub switch (V.getid ()) {                Case R.id.button1:intent Intent = new Intent (this, testutiljar.class);                StartActivity (Intent);        Break }    }}

    Also register Testutiljar this activity in manifest.
    <activity
    Android:name= "Com.example.selfjar.TestUtilJar"
    >
    </activity>

</pre>

Plan one is that the official approach should be better suited to their own companies to develop and cite open source code, but sometimes need to provide support to third-party companies, of course, this time do not want them to see our source code, the adoption of scenario two is more ideal.


Android packs activity and other classes into jar packages for third-party calls

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.