Android 如何通知wifi网络状态更改?
我正在编写一个通过wifi连接到telnet服务器的应用程序。我有一个管理套接字连接的服务。这一切都可以正常工作,但当手机睡眠时,它会断开wifi收音机的连接,从而导致插座连接中断(并引发SocketException) 我觉得我应该能够设置一个广播接收器,当wifi网络连接丢失时,会调用其onResume()方法,这将允许我优雅地关闭套接字,并在网络立即重新连接时重新打开它。但我在文件中或通过搜索都找不到类似的东西 服务代码在这里,如果你想要它,谢谢你的帮助,我真的很感激Android 如何通知wifi网络状态更改?,android,Android,我正在编写一个通过wifi连接到telnet服务器的应用程序。我有一个管理套接字连接的服务。这一切都可以正常工作,但当手机睡眠时,它会断开wifi收音机的连接,从而导致插座连接中断(并引发SocketException) 我觉得我应该能够设置一个广播接收器,当wifi网络连接丢失时,会调用其onResume()方法,这将允许我优雅地关闭套接字,并在网络立即重新连接时重新打开它。但我在文件中或通过搜索都找不到类似的东西 服务代码在这里,如果你想要它,谢谢你的帮助,我真的很感激 package co
package com.wingedvictorydesign.LightfactoryRemote;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.text.Editable;
import android.util.Log;
import android.widget.Toast;
import android.os.Debug;
/**
* @author Max
*/
public class TelnetService extends Service {
private final int DISCONNECTED = 0;
private final int CONNECTED = 1;
// place notifications in the notification bar
NotificationManager mNM;
protected InputStream in;
protected OutputStream out;
protected Socket socket;
// the socket timeout, to prevent blocking if the server connection is lost.
protected final int SO_TIMEOUT = 250;
// holds the incoming stream from socket until it is ready to be read.
BufferedReader inputBuffer;
final RemoteCallbackList<TelnetServiceCallback> mCallbacks =
new RemoteCallbackList<TelnetServiceCallback>();
@Override
public void onCreate() {
super.onCreate();
Log.d("LightfactoryRemote", "TelnetService onCreate()");
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}// end onCreate()
@Override
public void onDestroy() {
super.onDestroy();
Log.d("LightfactoryRemote", "TelnetService onDestroy()");
// Cancel the persistent notification, if it hasn't been already.
mNM.cancel(R.string.telnet_service_connected);
}// end onDestroy()
@Override
public IBinder onBind(Intent intent) {
Log.d("LightfactoryRemote", "TelnetService onBind()");
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
super.onUnbind(intent);
Log.d("LightfactoryRemote", "TelnetService onUnBind()");
return true;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("TelnetService", "TelnetService onStart()");
}
private final TelnetServiceInterface.Stub mBinder =
new TelnetServiceInterface.Stub() {
public void registerCallback(TelnetServiceCallback cb) {
if (cb != null) mCallbacks.register(cb);
}
public void unregisterCallback(TelnetServiceCallback cb) {
if (cb != null) mCallbacks.unregister(cb);
}
public String connectToTelnet(String Host, int Port)
throws RemoteException {
// android.os.Debug.waitForDebugger();
String hostInfo = null;
try {
socket = new java.net.Socket();
socket.setSoTimeout(SO_TIMEOUT);
socket.connect(new InetSocketAddress(Host, Port), 10000); //setup
// the port with a timeout of 10sec.
out = socket.getOutputStream();
/*
* in is wrapped in a reader, then in a Buffered reader. This is
* supposedly better for performance, and allows us to read a
* line at a time using the readLine() method.
*/
inputBuffer = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (java.io.IOException e) {
Log.d("TelnetService.java", "Connection failed! " + e);
/*
* if the connection fails, return null for serverResponse,
* which will be handled appropriately on the client side.
*/
return hostInfo;
}
// now that the command has been sent, read the response.
hostInfo = readBuffer();
Log.d("TelnetService.java", hostInfo);
// notify the user that we are connected
showNotification(CONNECTED, Host, Port);
return hostInfo;
}// end connectToTelnet
/**
* Tests for a currently active connection. Three cases must be
* distinguished. 1. A connection attempt has not been made. Return
* false. 2. A connection attempt has been made, and socket is
* initialized, but no connection is active. isConnected() returns
* false. 3. A connection is active. isConnected() returns true.
*/
public boolean areYouThere() {
if (socket != null) {
boolean connectStatus = socket.isConnected();
return connectStatus;
} else {
return false;
}
}// end areYouThere
public void disconnect() {
try {
if (inputBuffer != null) {
inputBuffer.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {}
// Cancel the persistent notification.
mNM.cancel(R.string.telnet_service_connected);
}// end disconnect()
/**
* send the string to the telnet server, and return the response from
* server If the connection is lost, an IOException results, so return
* null to be handled appropriately on the client-side.
*
* @throws RemoteException
*/
public String sendToTelnet(String toTelnet) throws RemoteException {
if (out == null) {
/*
* if out is still null, no connection has been made. Throw
* RemoteException to be handled on the client side.
*/
throw new RemoteException();
} else {
byte arr[];
arr = (toTelnet + "\r" + "\n").getBytes();
try {
out.write(arr);
// now that the command has been sent, read the response.
String serverResponse = readBuffer();
return serverResponse;
} catch (IOException e) {
/*
* if a connection was made, but then lost, we end up here.
* throw a Remoteexception for handling by the client.
*/
Log.d("TelnetService", "IO exception" + e);
disconnect();
throw new RemoteException();
}
}// end else
}// end sendToTelnet
};// end ConnectService.Stub class
public String readBuffer() {
StringBuilder serverResponse = new StringBuilder();
int character;
try {
// keep reading new lines into line until there are none left.
while (inputBuffer.ready()) {
/*
* as each character is read, append it to serverResponse,
* throwing away the carriage returns (which read as glyphs),
* and the ">" prompt symbols.
*/
character = inputBuffer.read();
if ((character != 13) && (character != 62)) {
serverResponse.append((char) character);
}
}
}// end try
catch (SocketTimeoutException e) {
Log.d("TelnetService read()", "SocketTimeoutException");
} catch (IOException e) {
Log.d("TelnetService read()", "read() IO exception" + e);
}
return serverResponse.toString();
}
/**
* Show a notification while this service is running.
*/
private void showNotification(int event, String Host, int Port) {
// In this sample, we'll use the same text for the ticker and the
// expanded notification
CharSequence notificationText = "Connected to " + Host + " : " + Port;
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(
R.drawable.notbar_connected, notificationText,
System.currentTimeMillis());
// set the notification not to clear when the user hits
// "Clear All Notifications"
notification.flags |= Notification.FLAG_NO_CLEAR;
// The PendingIntent to launch our activity if the user selects this
// notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, LightfactoryRemote.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this,
getText(R.string.telnet_service_connected), notificationText,
contentIntent);
// Send the notification.
// We use a string id because it is a unique number. We use it later to
// cancel.
mNM.notify(R.string.telnet_service_connected, notification);
}// end showNotification()
} // end TelnetConnection
package com.wingedvictorydesign.LightfactoryRemote;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.net.InetSocketAddress;
导入java.net.Socket;
导入java.net.SocketException;
导入java.net.SocketTimeoutException;
导入android.app.Notification;
导入android.app.NotificationManager;
导入android.app.pendingent;
导入android.app.Service;
导入android.content.Intent;
导入android.os.IBinder;
导入android.os.RemoteCallbackList;
导入android.os.RemoteException;
导入android.text.Editable;
导入android.util.Log;
导入android.widget.Toast;
导入android.os.Debug;
/**
*@author Max
*/
公共类TelnetService扩展服务{
专用最终int断开=0;
连接的专用最终int=1;
//在通知栏中放置通知
通知经理mNM;
受保护的输入流;
保护输出流输出;
保护插座;
//套接字超时,以防止服务器连接丢失时阻塞。
受保护的最终int SO_超时=250;
//保存来自套接字的传入流,直到它准备好读取为止。
BufferedReader输入缓冲区;
最终远程回调列表mCallbacks=
新的RemoteCallbackList();
@凌驾
public void onCreate(){
super.onCreate();
Log.d(“LightfactoryRemote”、“TelnetService onCreate()”;
mNM=(NotificationManager)getSystemService(通知服务);
}//结束onCreate()
@凌驾
公共空间{
super.ondestory();
Log.d(“LightfactoryRemote”、“TelnetService onDestroy()”;
//取消持久通知(如果尚未执行)。
mNM.cancel(R.string.telnet\u服务\u已连接);
}//结束onDestroy()
@凌驾
公共IBinder onBind(意向){
Log.d(“LightfactoryRemote”、“TelnetService onBind()”;
返回mBinder;
}
@凌驾
公共布尔onUnbind(意图){
super.onUnbind(意图);
Log.d(“LightfactoryRemote”、“TelnetService onUnBind()”;
返回true;
}
@凌驾
公共无效启动(Intent Intent,int startId){
super.onStart(intent,startId);
Log.d(“TelnetService”、“TelnetService onStart()”;
}
私有最终TelnetServiceInterface.Stub mBinder=
新的TelnetServiceInterface.Stub(){
公共无效注册表回调(TelnetServiceCallback cb){
如果(cb!=null)mCallbacks.register(cb);
}
公共无效注销回调(TelnetServiceCallback cb){
如果(cb!=null)mCallbacks.unregister(cb);
}
公共字符串connectToTelnet(字符串主机,int端口)
抛出远程异常{
//android.os.Debug.waitForDebugger();
字符串hostInfo=null;
试一试{
socket=新的java.net.socket();
套接字设置超时(SO_超时);
socket.connect(新的InetSocketAddress(主机,端口),10000);//安装
//该端口的超时时间为10秒。
out=socket.getOutputStream();
/*
*in被包装在读卡器中,然后被包装在缓冲读卡器中
*据说性能更好,并允许我们阅读
*使用readLine()方法一次执行一行。
*/
inputBuffer=新的BufferedReader(新的InputStreamReader(
getInputStream());
}捕获(java.io.ioe异常){
Log.d(“TelnetService.java”,“连接失败!”+e);
/*
*如果连接失败,请为serverResponse返回null,
*这将在客户端得到适当处理。
*/
返回主机信息;
}
//现在命令已经发送,请阅读响应。
hostInfo=readBuffer();
Log.d(“TelnetService.java”,hostInfo);
//通知用户我们已连接
showNotification(已连接、主机、端口);
返回主机信息;
}//终端连接终端
/**
*测试当前活动的连接。必须有三种情况
*1.未进行连接尝试。返回
*false.2.已尝试连接,并且套接字为空
*已初始化,但没有活动的连接。isConnected()返回
*false.3.连接处于活动状态。isConnected()返回true。
*/
公共布尔值areYouThere(){
if(套接字!=null){
布尔connectStatus=socket.isConnected();
返回连接状态;
}否则{
返回false;
}
}//你在这儿吗
公共空间断开连接(){
试一试{
if(inputBuffer!=null){
inputBuffer.close();
}
if(套接字!=null){
socket.close();
}
}捕获(IOE){}
//取消预订
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<receiver android:name="com.myBroadcastReceiver" >
<intent-filter>
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
public class myBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
NetworkInfo networkInfo = intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
Log.d(AppConstants.TAG, "Type : " + networkInfo.getType()
+ "State : " + networkInfo.getState());
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//get the different network states
if (networkInfo.getState() == NetworkInfo.State.CONNECTING || networkInfo.getState() == NetworkInfo.State.CONNECTED) {
}
}
}
}
}