Android package Activity and other classes into jar packages for third-party calls.

Source: Internet
Author: User

Android package Activity and other classes into jar packages for third-party calls.


When developing a java project, a project may be divided into multiple modules. To achieve decoupling and independence between modules and improve the reusability of modules, generally, projects are divided into multiple java projects by module for development. Finally, system integration is realized through jar packages and other engineering dependencies to improve module coupling and reuse.

Now we have developed the Android project through practice and summary and found that this method is particularly necessary. For example, to develop an android video playback function, there must be a playback and download module, if new features are constantly added in a project without being opened, every R & D of the product will constantly add and modify features, and maintenance will become increasingly difficult at last, with more and more bugs and mutual promotion, this method can avoid this situation. Second, the download module is a module used by many apps. It is constantly improved and optimized independently and can be used by different apps as a component, this improves the code decoupling, reusability, and efficiency of the module.

Due to the special nature of Android, android not only has java files but also res files. It is necessary to study how to package resource files and Activity files into jar files for other projects to call, find the following two solutions.

Solution 1:

According to the official documents of Android, set one project as a reference library and add a reference for this library to another project.

The simple method is

Add a line to project. properties in TestJar of the referenced project

 android.library=true

Add

 android.library=false android.library.reference.1=../TestJar

1 indicates the serial number of the referenced package, and "../TestJar" indicates the path of the referenced project.

In Eclipse, perform the following operations:

    Set a normal android project as a library project
    The Library Project is also a standard Android project. Therefore, you must first create a common Android project. This project can have any name, package name, and other fields to be set.
    Set the project to a database project as follows:
    1) In Package Explorer, right-click the project folder (TestJar) and click Properties.
    2) In the Properties window, select "Android". The Library Attribute is displayed on the lower right side.
    3) Select "is Library" and click "Apply.
    4) Click OK to close Properties.
    At this time, this project becomes a library project. Of course, a pure java project can also become a library project, which is very simple. It is OK to execute the above four steps. Other Program projects can reference this library project.


    Reference Library Project
    If your developed application wants to call the code and resources in the library project, the reference steps are as follows:
    1) In Package Explorer, right-click the project folder (TestJar) and click Properties.
    2) In the Properties window, select "Android". The Library Attribute is displayed on the lower right side.
    3) Click Add to open the Project Selection dialog box.
    4) Select the library project to be added from the list of available library projects, and click OK.
    5) Close the dialog box and click Apply (in the Properties window ).
    6) Click OK to close the Properties window.
    After completing the above six steps, Eclipse will re-build the project and include the libraries in the project.



      If you want to add references to multiple library projects, you can use up and down to set their relative priority and merge order. When the tool merges referenced databases, the order is from low-priority (below the List) to high-priority (above the list ). If more than one database defines the same resource ID, this tool selects a resource with a higher priority. Applications have the highest priority.

      Solution 2:

      You can export the JAR package to other projects for reference. If there is no resource package, you can export the jar package directly. The following describes how to package the Jar package and reference it when a resource package exists.

      Steps:

        Create a project named TestJar, which is to be packaged into a jar project.

          Note: The MResource class is very important. It is mainly used to obtain the resource ID Based on the Resource Name through reflection (in fact, the system also comes with the method getResources () to obtain the resource ID Based on the Resource Name (). getIdentifier ("main_activity", "layout", getPackageName (); the first parameter is the name of the resource, and the second parameter is the type of the resource, such as layout and string, the third is the package name)

          The MRsource. java code is as follows:
          Import android. content. context;/*** obtain its ID Value Based on the Resource name ** @ author yangzy */public class MResource {public static int getIdByName (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) {I F (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 ;}}
          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);}}


          TestUtilJar. java implementation is relatively simple. After an image is clicked, a Toast is displayed.
          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();            }        });    }}


          The layout file is as follows:
                   
                
               
          Export TestJar as a Jar package, export all resource files, and only export the source code

          6. Import the exported testjar1.jar file to the project to be referenced, and copy it to the libs first.
          <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + 1 + keys/dPDtb21xNfK1LTOxLz + yKuyv7 + keys/keys + CjxwPjxpbWcgc3JjPQ = "http://www.2cto.com/uploadfile/Collfiles/20150302/2015030209421394.jpg" alt = "\">


            Reference 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 button;    @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;        }    }}

            At the same time, register the Activity TestUtilJar in Manifest.
            Android: name = "com. example. selfjar. TestUtilJar"
            >


            Solution 1: The official method should be better suited for your company to develop and reference open source code, but sometimes it is necessary to provide support to third-party companies, of course, we don't want them to see our source code at this time. It is ideal to adopt solution 2 at this time.


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.