Android程序中嵌入Mina包

做桌面的网络通信常用mina框架,最近做一个android的应用,为简化开发过程,欲使用mina框架

 

其实将mina整合进android程序就是将第三方jar包引入android程序的过程,在网上找到很多说法,比如新建一个User

 

library 什么的 = = ,初步分析这些都是ctrl+c,ctrl+v产生的。经验证,编译通过、运行出错,错误原因是找不到Class ……

 

下面是我的做法:

 

1. 在本工程的目录下新建一个libs文件夹


2.将mina所需jar包复制到libs中


3.右键单击工程设置build path-->添加外部jar-->选择刚刚libs文件夹中的jar文件

 

ok 这样外部jar包就引入了.

 

然后在AndroidManifest文件中加入网络访问权限,下面这句插在</manifest>标签前面就可以

 

 

<uses-permission android:name="android.permission.INTERNET"/> 

 

 下面贴出测试工程的三个类的代码:

 

 

package org.m;

import android.app.Activity;
import android.os.Bundle;
/**入口类*/
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		new Thread(){
		public void run(){
        new MinaClient();}}.start();	
    }
}
import java.net.InetSocketAddress;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**客户端*/
public class MinaClient {
	public static final int PORT = 9988;
    	public static final String IP = "127.0.0.1";
    	private static ConnectFuture cf;

     MinaClient() {
        NioSocketConnector connector = new NioSocketConnector();
        DefaultIoFilterChainBuilder chain = connector.getFilterChain();
        ProtocolCodecFilter filter = new ProtocolCodecFilter(new ObjectSerializationCodecFactory());
        chain.addLast("myChin", filter);
        connector.setHandler(new ClientSessionHandler());
        connector.setConnectTimeout(30);
        cf = connector.connect(new InetSocketAddress(IP, 9988));
        cf.awaitUninterruptibly();
        cf.getSession().getCloseFuture().awaitUninterruptibly();
    }

}
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;

import android.util.Log;


public class ClientSessionHandler extends IoHandlerAdapter{

	@Override
	public void sessionOpened(IoSession session){
		Log.e("ok", "i am ready!");
	}
	
	@Override
	public void sessionClosed(IoSession session){
	}
	
	@Override
	public void messageReceived(IoSession session,Object message){
	}
}
 

 

你可能感兴趣的:(android)