android_socket_switch

本文介绍了一个简单的 Android 应用示例,该应用通过 Socket 连接远程服务器并发送 ON 和 OFF 指令。文章包含了 activity_main.xml 布局文件、MainActivity.java 业务逻辑实现以及 AndroidManifest.xml 配置文件。

1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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="echo.cn.socket.MainActivity">

    <EditText
        android:id="@+id/addr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="35dp"
        android:hint="请输入IP地址"/>

    <Button
        android:id="@+id/on"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/addr"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="35dp"
        android:text="ON" />

    <Button
        android:id="@+id/off"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/on"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="35dp"
        android:text="OFF" />

</RelativeLayout>
2.MainActivity.java

package echo.cn.socket;


import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText addr;
    private Button on, off;
    private Socket socket;
    private PrintStream output;
    private boolean isLinked = false;
    /* 服务器端口 */
    private final int HOST_PORT = 9999;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addr = (EditText) findViewById(R.id.addr);
        on = (Button) findViewById(R.id.on);
        off = (Button) findViewById(R.id.off);

        on.setOnClickListener(this);
        off.setOnClickListener(this);

        off.setEnabled(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.on:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isLinked){
                            socket();
                        }
                        if (isLinked){
                            turnON();
                        }
                    }
                }).start();
                if (isLinked){
                    off.setEnabled(true);
                    on.setEnabled(false);
                }
                break;
            case R.id.off:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        turnOFF();
                    }
                }).start();
                on.setEnabled(true);
                off.setEnabled(false);
                break;
            default:
                break;
        }
    }

    private void socket() {
        String ip = addr.getText().toString();
        Pattern pattern = Pattern.compile("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
        Matcher matcher = pattern.matcher(ip);
        if(matcher.matches()){
            try {
                socket = new Socket(ip, HOST_PORT);
                output = new PrintStream(socket.getOutputStream(), true, "utf-8");
                isLinked = true;
            } catch (Exception e) {
                System.out.println("host exception: " + e.toString());
            }
        }
    }

    private void turnOFF() {
        output.print("off");
    }

    private void turnON() {
        output.print("on");
    }
}

3.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="echo.cn.socket">

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

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

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

</manifest>



package com.intl.SmartWeather; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.StrictMode; import android.widget.Toast; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Service_Socket extends Service { private static final String strIPAddr = "127.0.0.1"; private static final int iPort = 8899; private static final int INTERVAL4TESTSOCKET = 7000; public static Socket socket; public static DataInputStream in; public static DataOutputStream out; public static boolean bSocketflag; public static String strMessageFor; public byte[] recvbuffer = new byte[1024]; private boolean IsRun = true; private byte[] dataSend; private ExecutorService mThreadPool; private Handler mHandler; private Timer mTimer; // 定义广播Action public static final String ACTION_SOCKET_DATA_RECEIVED = "com.intl.SmartWeather.ACTION_SOCKET_DATA_RECEIVED"; public static final String ACTION_SOCKET_STATUS_CHANGED = "com.intl.SmartWeather.ACTION_SOCKET_STATUS_CHANGED"; private final IBinder mBinder = new LocalBinder(); public class LocalBinder extends Binder { public Service_Socket getService() { return Service_Socket.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void onCreate() { //Android 4.0+ the socket communication must be added StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build()); bSocketflag = false; strMessageFor = "MainActivity"; //create threadpool mThreadPool = Executors.newCachedThreadPool(); socketConnect(); socketRecv(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: socketTest(); break; case 2: Toast.makeText(getApplicationContext(), "Connected Succeed", Toast.LENGTH_SHORT).show(); sendSocketStatusBroadcast(true); break; case 3: Toast.makeText(getApplicationContext(), "Connected Failed", Toast.LENGTH_SHORT).show(); sendSocketStatusBroadcast(false); break; } } }; mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { Message msg = mHandler.obtainMessage(); msg.what = 1; mHandler.sendMessage(msg); } }, 500, INTERVAL4TESTSOCKET); } @Override public void onDestroy() { super.onDestroy(); socketDisconnect(); if (mTimer != null) { mTimer.cancel(); mTimer = null; } IsRun = false; bSocketflag = false; } //Broadcast the socket data public void sendMsgtoActivty(String msg) { Intent intent = new Intent(ACTION_SOCKET_DATA_RECEIVED); intent.putExtra("message", msg); sendBroadcast(intent); } // Broadcast socket data with byte array public void sendDataToActivity(byte[] data) { Intent intent = new Intent(ACTION_SOCKET_DATA_RECEIVED); intent.putExtra("data", data); sendBroadcast(intent); } // Broadcast socket connection status private void sendSocketStatusBroadcast(boolean isConnected) { Intent intent = new Intent(ACTION_SOCKET_STATUS_CHANGED); intent.putExtra("connected", isConnected); sendBroadcast(intent); } // Thread for disconnect socket public void socketDisconnect() { mThreadPool.execute(new Runnable() { @Override public void run() { if (bSocketflag) { try { in.close(); out.close(); socket.close(); bSocketflag = false; sendSocketStatusBroadcast(false); } catch (Exception e) { e.printStackTrace(); } } } }); } // Thread for connect socket public void socketConnect() { socketDisconnect(); mThreadPool.execute(new Runnable() { @Override public void run() { try { socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(strIPAddr, iPort); socket.connect(socketAddress, 5000); // 5 seconds timeout socket.setSoTimeout(5000); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); bSocketflag = true; Message msg = mHandler.obtainMessage(); msg.what = 2; mHandler.sendMessage(msg); } catch (Exception e) { bSocketflag = false; e.printStackTrace(); Message msg = mHandler.obtainMessage(); msg.what = 3; mHandler.sendMessage(msg); } } }); } public void socketReconnect() { socketDisconnect(); mThreadPool.execute(new Runnable() { @Override public void run() { try { Thread.sleep(100); socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(strIPAddr, iPort); socket.connect(socketAddress, 5000); socket.setSoTimeout(5000); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); bSocketflag = true; Message msg = mHandler.obtainMessage(); msg.what = 2; mHandler.sendMessage(msg); } catch (Exception e) { bSocketflag = false; e.printStackTrace(); Message msg = mHandler.obtainMessage(); msg.what = 3; mHandler.sendMessage(msg); } } }); } // Thread for test socket public void socketTest() { mThreadPool.execute(new Runnable() { @Override public void run() { if (bSocketflag) { try { socket.sendUrgentData(0xFF);// connected test } catch (Exception e) { socketReconnect(); } } else { socketReconnect(); } } }); } // Thread for send socket public void socketSend(byte[] data) { dataSend = data; socketTest(); mThreadPool.execute(new Runnable() { @Override public void run() { if (bSocketflag) { try { out.write(dataSend); out.flush(); Log.d("Service_Socket", "Data sent: " + bytesToHex(dataSend)); } catch (Exception e) { e.printStackTrace(); socketReconnect(); } } } }); } // Thread for receive socket public void socketRecv() { mThreadPool.execute(new Runnable() { @Override public void run() { while (IsRun) { try { if (bSocketflag) { int iCount = in.read(recvbuffer); if (iCount != -1) { byte[] receivedData = new byte[iCount]; System.arraycopy(recvbuffer, 0, receivedData, 0, iCount); // Send received data to activity via broadcast sendDataToActivity(receivedData); Log.d("Service_Socket", "Data received, length: " + iCount); } } Thread.sleep(100); } catch (Exception e) { // Don't print stack trace for timeout exceptions (normal behavior) if (!(e instanceof java.net.SocketTimeoutException)) { e.printStackTrace(); } } } } }); } // Utility method to convert byte array to hex string for logging private String bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X ", b)); } return sb.toString(); } }补全并输出完整代码
09-29
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值