andrlid 局域网无线连接设备

源码下载地址:https://pan.baidu.com/s/1MlTLixPs376M5rG1iFndkQ

很久做了一个demo ,感觉挺好用的,分享出来给大家,具体想看源码的可以直接下载,这里可以看一下流程

网上有很多关于wifi 局域网下使用adb 无线连接设备,进行调试。我自己也写了一个 ,加强了一下功能,在网线情况下也可以使用adb

直接上菜:

代码比较简单,直接看吧

package cdl.yisheng.demo.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

/**
 * 获取网络连接的工具类
 * Created by chengguo on 2016/3/17.
 */
public class IntenetUtil {

    //没有网络连接
    public static final int NETWORN_NONE = 0;
    //wifi连接
    public static final int NETWORN_WIFI = 1;
    //手机2.3.4G网络
    public static final int NETWORK_MOBILE = 2;
    //以太网
    public static final int NETWORK_YITAI_NET = 3;

    /**
     * 获取当前网络连接类型
     *
     * @param context
     * @return
     */
    public static int getNetworkState(Context context) {
        //获取系统的网络服务
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //如果当前没有网络
        if (null == connManager)
            return NETWORN_NONE;
        //获取当前网络类型,如果为空,返回无网络
        NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
        if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
            return NETWORN_NONE;
        }
        // 判断是不是连接的是不是wifi
        NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (null != wifiInfo) {
            NetworkInfo.State state = wifiInfo.getState();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    return NETWORN_WIFI;
                }
        }
        // 如果不是wifi,则判断当前连接的是运营商的哪种网络2g、3g、4g等
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (null != networkInfo) {
            NetworkInfo.State state = networkInfo.getState();
            String strSubTypeName = networkInfo.getSubtypeName();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    switch (activeNetInfo.getSubtype()) {
                        case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
                        case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
                        case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN:
                        case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        case TelephonyManager.NETWORK_TYPE_EHRPD:
                        case TelephonyManager.NETWORK_TYPE_HSPAP:
                        case TelephonyManager.NETWORK_TYPE_LTE:
                            return NETWORK_MOBILE;
                        default:
                            //中国移动 联通 电信 三种3G制式
                            if (strSubTypeName.equalsIgnoreCase("TD-SCDMA") || strSubTypeName.equalsIgnoreCase("WCDMA") || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                                return NETWORK_MOBILE;
                            } else {
                                return NETWORK_YITAI_NET;
                            }
                    }
                }
        }
        return NETWORK_YITAI_NET;
    }
}

adb工具类

package cdl.yisheng.demo.util;

import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class RootCmd {
    private static final String TAG = "RootCmd";
    private static boolean mHaveRoot = false;

    public static boolean haveRoot() {
        if (!mHaveRoot) {
            int ret = execRootCmdSilent("echo test"); // 通过执行测试命令来检测
            if (ret != -1) {
                Log.i(TAG, "have root!");
                mHaveRoot = true;
            } else {
                Log.i(TAG, "not root!");
            }
        } else {
            Log.i(TAG, "mHaveRoot = true, have root!");
        }
        return mHaveRoot;
    }


    /**
     * 应用程序运行命令获取 Root权限,设备必须已破解(获得ROOT权限)
     *
     * @param command 命令:String apkRoot="chmod 777 "+getPackageCodePath(); RootCommand(apkRoot);
     * @return 应用程序是/否获取Root权限
     */
    public static boolean RootCommand(String command) {
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        Log.d("*** DEBUG ***", "Root SUC ");
        return true;
    }

    // 执行命令但不关注结果输出
    public static int execRootCmdSilent(String cmd) {
        int result = -1;
        DataOutputStream dos = null;
        try {
            Process p = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(p.getOutputStream());
            Log.i(TAG, cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            p.waitFor();
            result = p.exitValue();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

adb连接设备工具类

package cdl.yisheng.demo.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * Utilities of Adb wifi
 *
 * @author zeyuec
 * @since 2013-07-15
 */
public class Utility {

    private final static String TAG = "adbwifi.utility";

    private static int configPort = 5555;

    // adb wifi port, default 5555
    public static int getPort() {
        return configPort;
    }

    // not used right now, 2013-07-16
    public static void setPort(int port) {
        configPort = port;
    }


    /**
     * 检查网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }
        return true;
    }


    // detect if wifi is connected
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        State state = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if (state == State.CONNECTED) {
            return true;
        } else {
            return false;
        }
    }

    // detect if adbd is running
    public static boolean getAdbdStatus() {
        int lineCount = 0;
        try {
            Process process = Runtime.getRuntime().exec("ps | grep adbd");
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String str = input.readLine();
            while (str != null) {
                lineCount++;
                str = input.readLine();
            }
            if (lineCount >= 2) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // set adb wifi service 
    public static boolean setAdbWifiStatus(boolean status) {
        Process p;
        try {
//            p = Runtime.getRuntime().exec("mount -o rw,remount /system");
            p = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(p.getOutputStream());
            os.writeBytes("setprop service.adb.tcp.port " + String.valueOf(getPort()) + "\n");
            os.writeBytes("stop adbd\n");
            if (status) {
                os.writeBytes("start adbd\n");
            }
            os.writeBytes("exit\n");
            os.flush();
            p.waitFor();
            Log.e("haha", "=============打开adb返回值 :" + p.exitValue());
            if (p.exitValue() != 255) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("haha", "=============打开adb异常 :" + e.toString());
            return false;
        }
    }
}

主要就是这几个工具类 ,看一下界面调用方法

package cdl.yisheng.demo.activity;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import cdl.yisheng.demo.R;
import cdl.yisheng.demo.util.IntenetUtil;
import cdl.yisheng.demo.util.RootCmd;
import cdl.yisheng.demo.util.Utility;
import cdl.yisheng.demo.util.WaitDialogUtil;
import cdl.yisheng.demo.util.WifiMgr;
import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;

public class MainActivity extends Activity implements View.OnClickListener {
    private TextView hint;
    private Button btn_open_close;
    private boolean toggleStatus = false;
    private TextView tv_wifi_name;
    private TextView tv_ip_address;
    private TextView tv_root_permission;
    private Handler handler = new Handler();
    WaitDialogUtil waitDialogUtil;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
                if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
                    try {
                        Thread.sleep(10000);
                        int tryTimes = 0;
                        String ipaddress = WifiMgr.getLocalNetIpAddress();
                        while (ipaddress == null && tryTimes < 0) {
                            Thread.sleep(1000);
                        }
                        resetToggleStatus();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    lockToggle();
                }
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        checkCameraPermission();
//        Intent localIntent = new Intent("android.intent.action.REBOOT");
//        localIntent.putExtra("nowait", 1);
//        localIntent.putExtra("interval", 1);
//        localIntent.putExtra("window", 0);
//        sendBroadcast(localIntent);
        initReceiver();
    }

    private void initView() {
        waitDialogUtil = new WaitDialogUtil(MainActivity.this);
        waitDialogUtil.showDialog("操作中...");
        btn_open_close = (Button) findViewById(R.id.btn_open_close);
        hint = (TextView) findViewById(R.id.hint);
        btn_open_close.setOnClickListener(this);
        tv_wifi_name = (TextView) findViewById(R.id.tv_wifi_name);
        tv_ip_address = (TextView) findViewById(R.id.tv_ip_address);
        tv_root_permission = (TextView) findViewById(R.id.tv_root_permission);
        tv_wifi_name.setOnClickListener(this);
        tv_ip_address.setOnClickListener(this);
        try {
            String apkRoot = "chmod 777 " + getPackageCodePath();
            boolean isRoot = RootCmd.RootCommand(apkRoot);
            Log.e("haha", "=========请求root权限状态===========" + isRoot);
        } catch (Exception e) {
            Log.e("haha", "=========00000===========" + e.toString());
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_wifi_name:
            case R.id.tv_ip_address:
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                break;
            case R.id.btn_open_close:
                if (!RootCmd.haveRoot()) {
                    showToast("设备没有 ROOT 权限");
                    return;
                }
                int netType = IntenetUtil.getNetworkState(MainActivity.this);
                switch (netType) {
                    case IntenetUtil.NETWORN_NONE:
                        showToast("当前无网络");
                        break;
                    case IntenetUtil.NETWORK_MOBILE:
                        showToast("手机网络");
                        break;
                    case IntenetUtil.NETWORN_WIFI:
                        openOrCloseAdb();
                        break;
                    case IntenetUtil.NETWORK_YITAI_NET:
                        changeNetYiTaiNet();
                        break;
                }
                break;
        }
    }

    public void changeNetYiTaiNet() {
        boolean ret = Utility.setAdbWifiStatus(!toggleStatus);
        if (ret) {
            toggleStatus = !toggleStatus;
            updateWifiIpInfo(toggleStatus);
        } else {
            showToast("something wrong");
        }
    }

    private void jujleWifiState() {
        int netType = IntenetUtil.getNetworkState(MainActivity.this);
        switch (netType) {
            case IntenetUtil.NETWORN_NONE:
                waitDialogUtil.dismiss();
                hint.setText("net is not connected");
                showToast("当前无网络");
                break;
            case IntenetUtil.NETWORK_MOBILE:
                waitDialogUtil.dismiss();
                hint.setText("手机网络");
                break;
            case IntenetUtil.NETWORN_WIFI:
                Utility.setAdbWifiStatus(true);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        resetToggleStatus();
                    }
                }, 1500);
                break;
            case IntenetUtil.NETWORK_YITAI_NET:
                Utility.setAdbWifiStatus(true);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        resetToggleStatus();
                    }
                }, 1500);
                break;
        }
    }

    private void resetToggleStatus() {
        if (waitDialogUtil != null) {
            waitDialogUtil.dismiss();
        }
        toggleStatus = Utility.getAdbdStatus();
        updateWifiIpInfo(toggleStatus);
    }

    private void lockToggle() {
        Utility.setAdbWifiStatus(false);
        toggleStatus = false;
        updateWifiIpInfo(toggleStatus);
        hint.setText("wifi is not connected");
        btn_open_close.setText("关闭adb");
        btn_open_close.setBackgroundResource(R.drawable.rect_circle_red);
    }

    public void openOrCloseAdb() {
        waitDialogUtil.showDialog("操作中");
        if (Utility.isWifiConnected(MainActivity.this)) {
            boolean ret = Utility.setAdbWifiStatus(!toggleStatus);
            if (ret) {
                toggleStatus = !toggleStatus;
                updateWifiIpInfo(toggleStatus);
            } else {
                showToast("something wrong");
            }
        } else {
            lockToggle();
        }
    }

    /***
     * 更新wifi信息
     */
    private void updateWifiIpInfo(boolean toggleStatus) {
        waitDialogUtil.dismiss();
        if (!toggleStatus) {
            hint.setText("");
            btn_open_close.setText("打开adb");
            btn_open_close.setBackgroundResource(R.drawable.rect_circle_blue);
            showToast("adb wifi service stopped");
        } else {
            String ipaddress = WifiMgr.getLocalNetIpAddress();
            hint.setText("adb connect " + ipaddress + ":" + String.valueOf(Utility.getPort()));
            btn_open_close.setText("关闭adb");
            btn_open_close.setBackgroundResource(R.drawable.rect_circle_red);
            showToast("adb wifi service started");
        }
        //===========标题wifi信息=========================================
        int netType = IntenetUtil.getNetworkState(MainActivity.this);
        boolean isRoot = RootCmd.haveRoot();
        tv_root_permission.setText("设备是否有root : " + isRoot);
        switch (netType) {
            case IntenetUtil.NETWORN_NONE:
                tv_wifi_name.setText("WIFI 未连接,点击设置WIFI");
                tv_ip_address.setText("WIFI 未连接,点击设置WIFI");
                break;
            case IntenetUtil.NETWORK_MOBILE:
                tv_wifi_name.setText("网络类型:手机网络");
                String ipNet = WifiMgr.getLocalNetIpAddress();
                tv_ip_address.setText("IP : " + ipNet);
                break;
            case IntenetUtil.NETWORN_WIFI:
                WifiInfo wifiInfo = WifiMgr.getInstance(MainActivity.this).getWifiInfo();
                String wifiName = wifiInfo.getSSID();
                tv_wifi_name.setText("WIFI : " + wifiName);
                String ipaddress = WifiMgr.getLocalNetIpAddress();
                tv_ip_address.setText("IP : " + ipaddress);
                break;
            case IntenetUtil.NETWORK_YITAI_NET:
                tv_wifi_name.setText("网络类型:以太网");
                String ipNet_yitai = WifiMgr.getLocalNetIpAddress();
                tv_ip_address.setText("IP : " + ipNet_yitai);
                break;
        }
    }


    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    public void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        super.onDestroy();
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    }

    private void showToast(String toast) {
        Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
    }

    /***
     * 检查相机权限,并去扫描文字
     */
    public void checkCameraPermission() {
        List permissonItems = new ArrayList();
        permissonItems.add(new PermissionItem(Manifest.permission.ACCESS_COARSE_LOCATION, "WIFI列表", R.drawable.permission_ic_phone));
        permissonItems.add(new PermissionItem(Manifest.permission.ACCESS_FINE_LOCATION, "WIFI连接", R.drawable.permission_ic_phone));
        permissonItems.add(new PermissionItem(Manifest.permission.READ_EXTERNAL_STORAGE, "读SD卡权限", R.drawable.permission_ic_phone));
        permissonItems.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "写SD卡权限", R.drawable.permission_ic_phone));
        permissonItems.add(new PermissionItem(Manifest.permission.RECORD_AUDIO, "MIC权限", R.drawable.permission_ic_phone));
        permissonItems.add(new PermissionItem(Manifest.permission.CAMERA, "相机权限", R.drawable.permission_ic_phone));
        permissonItems.add(new PermissionItem(Manifest.permission.READ_PHONE_STATE, "获取电话状态", R.drawable.permission_ic_phone));
        HiPermission.create(MainActivity.this)
                .permissions(permissonItems)
                .checkMutiPermission(new PermissionCallback() {

                    @Override
                    public void onClose() {
                    }

                    @Override
                    public void onFinish() {
                        initView();
                        jujleWifiState();
                    }

                    @Override
                    public void onDeny(String permisson, int position) {
                    }

                    @Override
                    public void onGuarantee(String permisson, int position) {
                    }
                });
    }


}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(安卓前端,java,android)