如何收到 wifi 网络状态变化的通知?

2024-04-06

我正在编写一个通过 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

注册一个BroadcastReceiver对于 ConnectivityManager.CONNECTIVITY_ACTION。在里面onReceive您可以调用的处理程序NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO)进而info.getType()并检查ConnectivityManager.TYPE_WIFI然后做你想做的事。 :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何收到 wifi 网络状态变化的通知? 的相关文章

随机推荐

  • C 程序中的 .eh_frame 部分有什么用?

    我有一个从 C 程序编译的静态链接可执行文件 objdump x a out表明存在 eh frame部分 甚至在之后strip s 为什么本节在 C 语言中很有用 非 C 程序 有什么风险剥离它 与strip R eh frame 根据
  • 如何使用 http://translate.google.com/ 翻译 Java 程序中的字符串?

    我想用http translate google com http translate google com 翻译字符串 现在我想从 java 程序发送一个字符串http translate google com http translat
  • 无法反转链表

    我试图反转链表 但是每当我执行以下函数时 我只得到最后一个元素 例如 如果列表之前包含 11 12 13 执行该函数后 它只包含13 请指出我的代码中的错误 void reverselist struct node a b c a NULL
  • 设计者生成的表适配器如何处理连接

    表适配器如何使用连接 稍微解释一下 它们是否会自动打开和关闭连接 或者如果我在调用表适配器方法之前已经打开了连接 它们是否会使用它并使其保持打开状态 Regards 如果您查看设计器生成的代码 您会发现如果存在连接 适配器会重用它 否则会创
  • 我可以让 vim 尊重我的 .gitignore 文件吗?

    我想知道是否有一种方法可以让 vim 读取 gitignore 文件并使用它们来确定自动完成文件名时不显示的选项 例如 在 python 中工作 我不想看到可供编辑的 pyc 文件 我认为 vim 有它自己的机制 我想知道如何将 gitig
  • 使用 brfs 进行观看和捆绑而不使用 watchify 的命令

    我正在尝试复制的行为watchify与brfs变换 但我需要使用brfs直接因为我想避免在使用时添加到脚本中的额外代码require使用 browserify watchify 使用brfs直接简单替换require theFile 及其内
  • Rplot() 或 ggplot2() 中的对数 y 轴刻度线

    我看到了理想的刻度线结构log y 情节在这张纸 http arxiv org pdf cond mat 0412004 图3b 3c 3d 它具有不带标签的短的 对数间隔的小刻度线 以及带标签的长的 对数间隔的主刻度线 有谁知道如何实现这
  • 如何在 Go 中验证电子邮件地址

    我检查了 StackOverflow 但找不到任何可以回答的问题如何用 Go 语言验证电子邮件 经过一番研究 我根据自己的需要找出并解决了这个问题 我有这个regex and 转函数 效果很好 import fmt regexp func
  • jquery如何向图像添加图钉并将位置保存到SQL

    如何固定图像并保存固定位置 I found 这个插件 http jsfiddle net uKkRh 1 但我不知道如何保存这些引脚的位置 这个想法就像谷歌地图一样 用户可以在其中放置任意数量的图钉 并将这些图钉位置保存到数据库中 下次登录
  • 如何从命令行列出 Github 包注册表存储库中的所有包?

    假设我们有 Github 包注册表存储库https maven pkg github com someOrganization https maven pkg github com someOrganization 如何将此存储库中的所有包
  • 加快随机森林速度的建议

    我正在做一些工作randomForest包 虽然效果很好 但可能很耗时 有人对加快速度有什么建议吗 我使用的是带有双核 AMD 芯片的 Windows 7 盒子 我知道 R 不是多线程 处理器 但很好奇是否有任何并行包 rmpi snow
  • 如何更改 Gstreamer 插件的等级?

    我已经下载并编译了 vaapi 插件集 对于某些特定情况它工作得很好 但它也破坏了我现有的许多管道 我想先修改 Gstreamer 以使用其他解码器 有没有办法在不修改原始源的情况下改变 Gstreamer 插件的等级 我在 Gstream
  • JSF 2.0 中的显式 url 重定向

    我下面有以下两页 你好 xhtml 由 hello jsf url 呈现
  • 访问 MS Access 应用程序中的原始代码

    我一直在尝试查找一些有关访问 MS Access 中的原始代码的信息 我使用 v2007 但可能应该适用于所有版本 举例来说 我想列出应用程序中每个代码隐藏表单和模块中的所有函数并列出它们的参数 你将如何实现这一目标 注意 我当然假设该应用
  • 如何使用 jq 过滤 JSON 对象数组?

    我有以下 JSON 输入 zk kafka InstanceType t2 medium zkMemory 16 kafkaMemory 8 InstanceType t2 small zkMemory 8 kafkaMemory 4 es
  • 限制 ADFS 2.0 使用特定 OU 而不是域级别访问

    考虑以下示例场景 我有一个用于生产 测试 和开发的单个 Active Directory 域 每个域在 OU 级别分开 我想在测试 OU 级别安装 ADFS 并且不希望在测试 OU ADFS 上经过身份验证的用户能够访问 读取和写入 其他
  • jQuery 简单值与 .val() 出现问题

    我有以下代码 document ready function alert font someClass val 这里有一个Fiddle http jsfiddle net 2wwzD 1 用它 有谁知道为什么我无法返回字体标签的值 我是否假
  • 求树的深度?

    我对二叉树和递归非常陌生 我的程序是找到树的高度 但我有点困惑为什么我的程序不起作用 struct Node int value Node left Node right int heightOfTree Node node if node
  • 当属性名称为参数时如何查询属性值?

    通常我们可以查询属性值 例如 Match n Product where n name iPhone X return n 但是 就我而言 我不知道应该匹配哪个属性 但我只知道值 在这种情况下属性名称就变成了一种变量 我想要这样的东西 Ma
  • 如何收到 wifi 网络状态变化的通知?

    我正在编写一个通过 wifi 连接到 telnet 服务器的应用程序 我有一个管理套接字连接的服务 一切正常 但当手机休眠时 它会断开 wifi 无线电 这会导致套接字连接中断 并抛出 SocketException 我觉得我应该能够设置一