我正在编写一个通过wifi连接到telnet服务器的应用程序.我有一个管理套接字连接的服务.一切正常,但是当手机休眠时,它会断开wifi无线电,导致套接字连接中断(并抛出SocketException).
我觉得我应该能够设置一个广播接收器,当wifi网络连接丢失时调用onResume()方法,这将允许我优雅地关闭套接字,并在网络立即重新打开它重新连接.但我在文档或搜索中找不到类似的东西.
服务代码在这里,如果你需要它,感谢您的帮助,我真的很感激!
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
解决方法:
为ConnectivityManager.CONNECTIVITY_ACTION注册broadcastReceiver.在onReceive处理程序中,您可以调用NetworkInfo info =(NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO),然后调用info.getType()并检查ConnectivityManager.TYPE_WIFI并执行您想要的 *** 作. 总结
以上是内存溢出为你收集整理的android – 如何通知wifi网络状态变化?全部内容,希望文章能够帮你解决android – 如何通知wifi网络状态变化?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)