android将项目打包成jar包使用

将Android打包成jar包供人使用,可利用java的反射技术,获取相应的id.方便使用者替换自己所需要的。

1.新建Android项目:ActivityLibrary,这就是需要我们打包成jar包的项目:

技术分享

2.MResource这个类的作用,就是利用J2SE反射技术获取相应的ID资源。Android SDK也提供了获取Id资源的方法:getResources().getIdentifier("main_activity", "layout", getPackageName());


看下MResource的代码:

package com.example.activitylibrary;

import android.content.Context;

/** 
 * 根据资源的名字获取其ID值 
 * @author howlaa
 */ 
public class MResource {
	
	//根据名称获取ID
    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) {  
                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;  
    }
    
    //获取ID数组
    public static int[] getIdsByName(Context context, String className, String name) {  
        String packageName = context.getPackageName();  
        Class r = null;  
        int[] ids = null;  
        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) && (desireClass.getField(name).get(desireClass) != null) && (desireClass.getField(name).get(desireClass).getClass().isArray()))  
            ids = (int[])desireClass.getField(name).get(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 ids;  
      } 
}

3.在layout下新建activity_main.xml:

<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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="28dp"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

4.看下mainactivity:

package com.example.activitylibrary;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity {
	
	String msg = "hello bitch";  
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(MResource.getIdByName(getApplication(), "layout", "activity_main"));
		
		TextView mTextView = (TextView) findViewById(MResource.getIdByName(getApplication(), "id", "textView1")); 
		mTextView.setText(msg);  
		
		Button mButton = (Button) findViewById(MResource.getIdByName(getApplication(), "id", "button1"));  
        
        mButton.setText(msg);  
        mButton.setOnClickListener(new OnClickListener() {  
              
            @Override  
            public void onClick(View v) {  
                Toast.makeText(getApplication(), msg, Toast.LENGTH_SHORT).show();  
            }  
        });  
	}

}

5.我们将ActivityLibrary工程打成Jar包。右键项目--->Export---->Java--->JAR file---->Next如下图

技术分享

技术分享

只需要SRC里面的代码就可以了。其他的去掉

6.新建一个项目APP2,使用刚才的jar包。把刚才导出的jar包拷贝到libs下面。

7.假如我们想使用上个项目中的mainactivity界面:我们可以在此有个跳转的代码:

public void btnClick(View view){
		Intent intent = new Intent();  
        intent.setClassName(getApplication(), "com.example.activitylibrary.MainActivity");  
        startActivity(intent);  
	}

8.在mainfest.xml中注册activitylibrary的mainActivity:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.app2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.activitylibrary.MainActivity"></activity>
    </application>

</manifest>

完毕。



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。