• Android与路由器连接服务


    界面UI:

        

    package my.work.Library;
    
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageButton;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    
    
    public class WsnActivty extends Activity {
        /** Called when the activity is first created. */
        private Button btnNetwork;
        private String strIpAddr = null;
        static TextView textTips;
        private ClientThread clientThread = null;
        private Message MainMsg;
        public static Handler mainHandler;
        static final int TIPS_UPDATE_UI = 3;   //tips_update_ui
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            initControl();
            initMainHandler();
      
        }
        private void initControl() {
            // TODO Auto-generated method stub
              btnNetwork = (Button) findViewById(R.id.btn_network);
              btnNetwork.setOnClickListener(new ButtonClick());
              
              textTips = (TextView) findViewById(R.id.Tips);
                textTips.setText(R.string.init_tips);
            
        }
        class ButtonClick implements OnClickListener {
            @Override
            public void onClick(View v) {
                
                switch (v.getId()) {
                case R.id.btn_network: // 连接网络
                    showDialog(WsnActivty.this);
                    break;
                    }
       }
        }
    
                // 显示连接对话框
                private void showDialog(Context context) {
                    final EditText editIP = new EditText(context);
                    editIP.setText("192.168.0.10");
    
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    // builder.setIcon(R.drawable.ic_launcher);
                    builder.setTitle("请输入服务器IP地址");
                    builder.setView(editIP);
                    builder.setPositiveButton("连接", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            strIpAddr = editIP.getText().toString();
                            boolean ret = isIPAddress(strIpAddr);
    
                            if (ret) {
                                textTips.setText("服务器IP地址:" + strIpAddr);
                            } else {
                                strIpAddr = null;
                                textTips.setText("IP地址不合法,请重新设置");
                                return;
                            }
    
                            clientThread = new ClientThread(strIpAddr);// 建立客户端线程
                            clientThread.start();
    
                            //mainTimer = new Timer();// 定时查询所有终端信息
                            //setTimerTask();
                        }
                    });
                    builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            if (clientThread != null) {
                                MainMsg = ClientThread.childHandler
                                        .obtainMessage(ClientThread.RX_EXIT);
                                ClientThread.childHandler.sendMessage(MainMsg);
                                textTips.setText("与服务器断开连接");
                            }
                        }
                    });
    
                    builder.show();
                }
            
            // 判断输入IP是否合法
            private boolean isIPAddress(String ipaddr) {
                boolean flag = false;
                Pattern pattern = Pattern
                        .compile("\b((?!\d\d\d)\d+|1\d\d|2[0-4]\d|25[0-5])\.((?!\d\d\d)\d+|1\d\d|2[0-4]\d|25[0-5])\.((?!\d\d\d)\d+|1\d\d|2[0-4]\d|25[0-5])\.((?!\d\d\d)\d+|1\d\d|2[0-4]\d|25[0-5])\b");
                Matcher m = pattern.matcher(ipaddr);
                flag = m.matches();
                return flag;
            }
            
            void initMainHandler() {
                mainHandler = new Handler() {
    
                    // 主线程消息处理中心
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                           case TIPS_UPDATE_UI:
                            String str = (String) msg.obj;  //连接成功
                            textTips.setText(str);
                            break;
                        }
                        super.handleMessage(msg);
                    }
                };
            }
    
    }
        

    子线程连接wifi代码代码

    package my.work.Library;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.SocketAddress;
    
    import android.content.Context;
    import android.os.Handler;
    import android.os.Looper;
    import android.os.Message;
    import android.widget.Toast;
    
    public class ClientThread extends Thread {
    
        private OutputStream outputStream = null;
        private InputStream inputStream = null;
        private Socket socket;
        private SocketAddress socketAddress;
        public static Handler childHandler;
        private boolean RxFlag = true;
        final int TEXT_INFO = 12;
        static final int RX_EXIT = 11;
        static final int TX_DATA = 10;
        Context mainContext;
        Message msg;
        private String strIP;
        final int SERVER_PORT = 33333;
        byte cNodeData[][] = new byte[4][5]; // [5] 0=温度 1=湿度 2=气体 3=灯
        int RxCount = 0, nRecvLen, index = 0;
        byte CheckSum;
        // byte strRxBuf[] = new byte[256];
        int ucRecvLen = 7;
    
        //获取WsnActivty.java 开辟子线程clientThread对象线程传递过来的ip地址
        public ClientThread(String ip) {
            strIP = ip;
        }
    
        // 连接网络
        void connect() {
            RxFlag = true;
            socketAddress = new InetSocketAddress(strIP, SERVER_PORT);
            socket = new Socket();
    
            try {
                socket.connect(socketAddress, SERVER_PORT);
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();
    
                msg = WsnActivty.mainHandler.obtainMessage(
                        WsnActivty.TIPS_UPDATE_UI, "连接成功");
                WsnActivty.mainHandler.sendMessage(msg);
                
    
            } catch (IOException e) {
                try {
                    sleep(10);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                msg = WsnActivty.mainHandler.obtainMessage(
                        WsnActivty.TIPS_UPDATE_UI, "无法连接到服务器");
                WsnActivty.mainHandler.sendMessage(msg);
                e.printStackTrace();
            } catch (NumberFormatException e) {
    
            }
        }
    
        void initChildHandler() {
    
            Looper.prepare(); // 在子线程中创建Handler必须初始化Looper
    
            childHandler = new Handler() {
                // 子线程消息处理中心
                public void handleMessage(Message msg) {
    
                    // 接收主线程及其他线程的消息并处理...
                    /**
                     * MainMsg = ClientThread.childHandler.obtainMessage(ClientThread.TX_DATA,
                     * len, 0, (Object) buffer);
                     * SendData(SendBuf, 7);
                     */
                    switch (msg.what) {
                    
    
                    case RX_EXIT:
                        RxFlag = false;
                        try {
                            if (socket.isConnected()) {
                                inputStream.close();
                                outputStream.close();
                                socket.close();
                            }
    
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
    
                        childHandler.getLooper().quit();// 结束消息队列
    
                        break;
    
                    default:
                        break;
                    }
    
                }
            };
    
            // 启动该线程的消息队列
            Looper.loop();
    
        }
    
        public void run() {
            connect();
            initChildHandler();
            msg = WsnActivty.mainHandler.obtainMessage(WsnActivty.TIPS_UPDATE_UI,
                    "与服务器断开连接");
            WsnActivty.mainHandler.sendMessage(msg);
        }
    
    }

    main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        
          <TextView 
              android:id="@+id/Tips"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="@string/init_tips"
              android:textSize="40px"
              android:textColor="#00ff00"
              />
           <Button 
            android:id="@+id/btn_network" 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login"
            android:textSize="40px"
            android:textColor="#00ff00"
            />
        
      
    </LinearLayout>

    string.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <string name="login">连接服务器</string>
        <string name="app_name">梧州学院图书馆刷卡入座系统</string>
        <string name="move">获取视频流</string>
         <string name="init_tips">提示:请先打开WiFi或GPRS再连接网络</string>
        
    
    </resources>

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.work.Library"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk android:minSdkVersion="15" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name=".WsnActivty"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
       
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
        <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    </manifest>
  • 相关阅读:
    Validation failed for one or more entities
    sql 存储过程
    SQL Server分页3种方案比拼
    case when 用法
    C#如何计算代码执行时间
    透过 Jet.OLEDB 读取 Excel里面的数据
    DataBinding?资料系结?资料绑定?
    ASP.NET的OutputCache
    我想写程序#3 之 「简单地设计自己的数据表(Table)」
    我想写程序#1 之 「先确立志向」
  • 原文地址:https://www.cnblogs.com/yihujiu/p/5982620.html
Copyright © 2020-2023  润新知