一、前言
相信大部分做wifi打印机打印的朋友都知道,第一步是要进行wifi搜索,看看当前局域网内已经启动的wifi打印机,然后再进行连接,具体的就不多说了,wifi打印这个模块写了已经很久了,现在才有空抽时间出来写一写总结,如果有什么不对的地方,希望能留言给个建议,多多交流交流。不多说,直接开撸。
二、打印机搜索工具类
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
/**
* @author Freak
* @date 2019/8/13.
*/
public class SearchPrinterUtil {
private Socket mSocket = null;
/**
* 打印机是否开启
*/
public boolean printerIsOpen = false;
/**
* 连接超时时间
*/
private final static int SOCKET_RECEIVE_TIME_OUT = 2500;
/**
* 是否搜索完成
*/
private boolean searchFinish = false;
public boolean isSearchFinish() {
return searchFinish;
}
/**
* 获取ip地址
*
* @param context 连接上下文
* @return
*/
public static String getIpAddress(Context context) {
//获取网络信息对象
NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
//判断是否连接网络
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
//网络是处于2G/3G/4G环境网络
// try {
// for (Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); enumeration.hasMoreElements(); ) {
// NetworkInterface networkInterface = enumeration.nextElement();
// for (Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses(); inetAddressEnumeration.hasMoreElements(); ) {
// InetAddress inetAddress = inetAddressEnumeration.nextElement();
// if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
// return inetAddress.getHostAddress();
// }
// }
// }
// } catch (SocketException e) {
// e.printStackTrace();
// }
return null;
} else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//网络是wifi环境网络
//获取wifi管理者
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//获取wifi信息
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//获取ip地址前三段
String ipv4 = intIPToStringIP(wifiInfo.getIpAddress());
return ipv4;
}
} else {
}
return null;
}
/**
* 将得到的int类型的IP转换为String类型,截取ip的前三段
*
* @param ip 获取的wifi地址信息
* @return
*/
public static String intIPToStringIP(int ip) {
return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "."
+ ((ip >> 16) & 0xFF) + ".";
}
/**
* 搜索已经打开的打印机
*
* @param ipAddress ip地址
* @param netPort 端口
* @return
*/
public boolean search(String ipAddress, int netPort) {
if (mSocket == null) {
try {
SocketAddress socketAddress = new InetSocketAddress(Inet4Address.getByName(ipAddress), netPort);
mSocket = new Socket();
mSocket.connect(socketAddress, SOCKET_RECEIVE_TIME_OUT);
if (mSocket.isConnected()) {
printerIsOpen = true;
}
} catch (UnknownHostException e) {
closeSocket();
return false;
} catch (IOException e) {
closeSocket();
return false;
}
} else {
try {
mSocket.close();
SocketAddress socketAddress = new InetSocketAddress(Inet4Address.getByName(ipAddress), netPort);
mSocket.connect(socketAddress, SOCKET_RECEIVE_TIME_OUT);
if (mSocket.isConnected()) {
printerIsOpen = true;
}
} catch (IOException e) {
closeSocket();
return false;
}
}
if (printerIsOpen) {
closeSocket();
}
return printerIsOpen;
}
/**
* 关闭socket
*/
private void closeSocket() {
if (mSocket != null) {
try {
mSocket.close();
mSocket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上面的就是打印机的搜索工具类,可以直接使用,从上面可以看出,打印机的搜索是使用socket进行连接的,具体的可以看代码,也很简单,需要注意的是ip的拼接,因为搜索打印是要搜索整个局域网下所有的ip,所以要根据设备连接的wifi信息,截取前三段,比如:192.168.1.1,前三段就是192.168.1,。搜索打印机的ip是要从1-255的,1肯定是不需要搜索的了,具体的看个人需求!当然,如果你本来就知道了当前wifi打印机的ip,也可以使用手动设置的方式去直接连接。
三、使用方式
/**
* 开始搜索打印机
*/
private void searchPrinter() {
mIpAddress = SearchPrinterUtil.getIpAddress(getActivity());
LogUtil.e("获取的ip地址--》" + mIpAddress);
if (TextUtils.isEmpty(mIpAddress)) {
DialogUtil.showToastDialog((AppCompatActivity) getActivity(), "温馨提示", "wifi暂未连接,请先连接wifi,然后使用打印机开关进行搜索打印机", "知道了");
} else {
RunThread runThread = new RunThread();
runThread.start();
}
}
/**
* 搜索打印机线程
*/
private class RunThread extends Thread {
public RunThread() {
}
@Override
public void run() {
super.run();
if (mExecutorService == null) {
mExecutorService = Executors.newCachedThreadPool();
}
//循环查找打印机 从2-255
for (int i = 2; i < 255; i++) {
final int index = i;
mExecutorService.execute(new Runnable() {
@Override
public void run() {
String ipAddress = mIpAddress + index;
SearchPrinterUtil mSearchPrinterUtil = new SearchPrinterUtil();
mSearchPrinterUtil.search(ipAddress, PORT);
if (mSearchPrinterUtil.printerIsOpen) {
Logger.e("开启的打印机--》" + ipAddress);
PrinterSettingBean printerSettingBean = new PrinterSettingBean();
printerSettingBean.setIp(ipAddress);
if (TextUtils.isEmpty(getIpAddress())) {
printerSettingBean.setSelect(false);
} else {
if (getIpAddress().equals(ipAddress)) {
printerSettingBean.setSelect(true);
} else {
printerSettingBean.setSelect(false);
}
}
mList.add(printerSettingBean);
mHandler.sendEmptyMessage(5);
return;
} else {
if (index == 254) {
mHandler.sendEmptyMessage(1);
}
}
}
});
}
}
}
/**
* 查找打印Handel、检查打印机状态Handel
*/
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
//断开连接
case 0:
//sp文件保存的是否开启打印
boolean isOpenPrinter = SharedPreferencesUtils.getBoolean(getActivity(), SharedPreferencesUtils.Printer_Open_Status);
if (isOpenPrinter) {
if (TextUtils.isEmpty(getIpAddress())) {
ToastUtil.show("请先设置打印机ip地址");
} else {
App.getPrinterUtilInstance().connectToDevice(getIpAddress(), 9100);
checkLinStatusBeforePrint(getIpAddress(), 9100);
}
} else {
ToastUtil.show("打印机未打开,请到打印机设置中打开打印机");
}
break;
//搜索结束
case 1:
setSharedPreferencesIpAddress();
break;
//正在连接
case 2:
//sp文件保存的是否开启打印
boolean mIsOpenPrinter = SharedPreferencesUtils.getBoolean(getActivity(), SharedPreferencesUtils.Printer_Open_Status);
if (mIsOpenPrinter) {
if (TextUtils.isEmpty(getIpAddress())) {
ToastUtil.show("请先设置打印机ip地址");
} else {
checkLinStatusBeforePrint(getIpAddress(), 9100);
}
} else {
ToastUtil.show("打印机未打开,请到打印机设置中打开打印机");
}
break;
case 4:
ToastUtil.show("连接成功");
break;
case 5:
mPrinterSettingAdapter.setNewData(mList);
break;
case 6:
ToastUtil.show("连接失败");
break;
default:
break;
}
}
};
private void setSharedPreferencesIpAddress() {
for (int i = 0; i < mList.size(); i++) {
if (mList.get(i).isSelect()) {
SharedPreferencesUtils.save(getActivity(), SharedPreferencesUtils.Printer_IP_Address, mList.get(i).getIp());
} else {
SharedPreferencesUtils.save(getActivity(), SharedPreferencesUtils.Printer_IP_Address, "");
}
}
}