在Android中使用套接字?

戈尔吉93

我要问的是一种方法或建议,如何重新实现我的从套接字接收数据的应用程序。我的应用程序现在连接到推送器服务,并从套接字获取数据。收到新事件(推送程序上的新数据)后,数据将更新到UI,并且用于接收数据的线程将等待新事件。

只要可以上网,就可以。当Internet断开时,不会重新建立套接字。

我有一个Android服务,可在其中接收数据,然后将结果发布给订阅者。订阅者然后使用数据调用UI更新方法,然后再次调用用于接收数据的android服务。

但是,在每个成功数据之后,首先在onResume活动和订阅者中调用android服务。但是,如果网络掉线,则不会再次启动该服务。我该如何处理?

我的第一个想法是,当网络断开时,我开始每2秒检查一次网络可用性的活动,如果网络可用,它将重新启动套接字。但是,它不能像我想要的那样可靠。

如果您需要查看代码,我会发布它。

鲁宾·那

您需要听CONNECTIVITY_ACTION。文档说:

网络连接发生了变化。连接已建立或丢失。受影响的网络的NetworkInfo作为附加发送。应该咨询一下发生了哪种连接事件。

如果这是从断开的网络进行故障转移的结果,则FAILOVER_CONNECTION布尔值布尔值将设置为true。

对于失去连接性的情况,如果连接性管理器正尝试连接(或已经连接)到另一个网络,则新网络的NetworkInfo也会作为额外的传递。这使广播的任何接收者都知道它们不必告诉用户没有数据流量将是可能的。相反,接收方应该很快会看到另一广播,这表明故障转移尝试成功了(因此仍然存在整体数据连接),或者故障转移尝试失败了,这意味着所有连接都丢失了。

对于断开事件,如果根本没有连接的网络,则布尔额外的EXTRA_NO_CONNECTIVITY设置为true。

常数值:“ android.net.conn.CONNECTIVITY_CHANGE”

请从此处参考以下代码段

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.util.HashMap;
import java.util.Iterator;

/**
 * A wrapper for a broadcast receiver that provides network connectivity
 * state information, independent of network type (mobile, Wi-Fi, etc.).
 * {@hide}
 */
public class NetworkConnectivityListener {
    private static final String TAG = "NetworkConnectivityListener";
    private static final boolean DBG = false;

    private Context mContext;
    private HashMap<Handler, Integer> mHandlers = new HashMap<Handler, Integer>();
    private State mState;
    private boolean mListening;
    private String mReason;
    private boolean mIsFailover;

    /** Network connectivity information */
    private NetworkInfo mNetworkInfo;

    /**
     * In case of a Disconnect, the connectivity manager may have
     * already established, or may be attempting to establish, connectivity
     * with another network. If so, {@code mOtherNetworkInfo} will be non-null.
     */
    private NetworkInfo mOtherNetworkInfo;

    private ConnectivityBroadcastReceiver mReceiver;

    private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
                mListening == false) {
                Log.w(TAG, "onReceived() called with " + mState.toString() + " and " + intent);
                return;
            }

            boolean noConnectivity =
                intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

            if (noConnectivity) {
                mState = State.NOT_CONNECTED;
            } else {
                mState = State.CONNECTED;
            }

            mNetworkInfo = (NetworkInfo)
                intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            mOtherNetworkInfo = (NetworkInfo)
                intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            mIsFailover =
                intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            if (DBG) {
                Log.d(TAG, "onReceive(): mNetworkInfo=" + mNetworkInfo +  " mOtherNetworkInfo = "
                        + (mOtherNetworkInfo == null ? "[none]" : mOtherNetworkInfo +
                        " noConn=" + noConnectivity) + " mState=" + mState.toString());
            }

            // Notifiy any handlers.
            Iterator<Handler> it = mHandlers.keySet().iterator();
            while (it.hasNext()) {
                Handler target = it.next();
                Message message = Message.obtain(target, mHandlers.get(target));
                target.sendMessage(message);
            }
        }
    };

    public enum State {
        UNKNOWN,

        /** This state is returned if there is connectivity to any network **/
        CONNECTED,
        /**
         * This state is returned if there is no connectivity to any network. This is set
         * to true under two circumstances:
         * <ul>
         * <li>When connectivity is lost to one network, and there is no other available
         * network to attempt to switch to.</li>
         * <li>When connectivity is lost to one network, and the attempt to switch to
         * another network fails.</li>
         */
        NOT_CONNECTED
    }

    /**
     * Create a new NetworkConnectivityListener.
     */
    public NetworkConnectivityListener() {
        mState = State.UNKNOWN;
        mReceiver = new ConnectivityBroadcastReceiver();
    }

    /**
     * This method starts listening for network connectivity state changes.
     * @param context
     */
    public synchronized void startListening(Context context) {
        if (!mListening) {
            mContext = context;

            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            context.registerReceiver(mReceiver, filter);
            mListening = true;
        }
    }

    /**
     * This method stops this class from listening for network changes.
     */
    public synchronized void stopListening() {
        if (mListening) {
            mContext.unregisterReceiver(mReceiver);
            mContext = null;
            mNetworkInfo = null;
            mOtherNetworkInfo = null;
            mIsFailover = false;
            mReason = null;
            mListening = false;
        }
    }

    /**
     * This methods registers a Handler to be called back onto with the specified what code when
     * the network connectivity state changes.
     *
     * @param target The target handler.
     * @param what The what code to be used when posting a message to the handler.
     */
    public void registerHandler(Handler target, int what) {
        mHandlers.put(target, what);
    }

    /**
     * This methods unregisters the specified Handler.
     * @param target
     */
    public void unregisterHandler(Handler target) {
        mHandlers.remove(target);
    }

    public State getState() {
        return mState;
    }

    /**
     * Return the NetworkInfo associated with the most recent connectivity event.
     * @return {@code NetworkInfo} for the network that had the most recent connectivity event.
     */
    public NetworkInfo getNetworkInfo() {
        return mNetworkInfo;
    }

    /**
     * If the most recent connectivity event was a DISCONNECT, return
     * any information supplied in the broadcast about an alternate
     * network that might be available. If this returns a non-null
     * value, then another broadcast should follow shortly indicating
     * whether connection to the other network succeeded.
     *
     * @return NetworkInfo
     */
    public NetworkInfo getOtherNetworkInfo() {
        return mOtherNetworkInfo;
    }

    /**
     * Returns true if the most recent event was for an attempt to switch over to
     * a new network following loss of connectivity on another network.
     * @return {@code true} if this was a failover attempt, {@code false} otherwise.
     */
    public boolean isFailover() {
        return mIsFailover;
    }

    /**
     * An optional reason for the connectivity state change may have been supplied.
     * This returns it.
     * @return the reason for the state change, if available, or {@code null}
     * otherwise.
     */
    public String getReason() {
        return mReason;
    }
}

syntax highlighted by Code2HTML, v. 0.9.1

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在Android中使用套接字接收文件

来自分类Dev

从Android使用HTTP或套接字

来自分类Dev

Python:在OSX中使用原始套接字

来自分类Dev

在C中使用套接字的HTTP请求

来自分类Dev

在任务中使用异步套接字

来自分类Dev

在Dart中使用UNIX套接字

来自分类Dev

在任务中使用异步套接字

来自分类Dev

在Java / Android中使用套接字多次发送二进制数据

来自分类Dev

如何在没有套接字的Android中使用TCP客户端?

来自分类Dev

使用asynctask android连接到套接字

来自分类Dev

Java Android使用套接字发送消息

来自分类Dev

在Perl中使用<$ socket [i]>读取数组中的套接字

来自分类Dev

如何在Python ssl套接字缓冲中使用select?

来自分类Dev

如何在Python中使用套接字创建通道

来自分类Dev

如何配置phoenix以在PostgreSQL中使用套接字

来自分类Dev

如何在套接字中使用raw_input

来自分类Dev

错误:在原始套接字中使用sendto()时,地址错误

来自分类Dev

在C#中使用C套接字时的问题

来自分类Dev

在Chrome扩展程序中使用UDP套接字

来自分类Dev

如何在Python中使用套接字创建通道

来自分类Dev

无法在C中使用套接字下载多个文件

来自分类Dev

在C#中使用.net UDP套接字发送字节

来自分类Dev

如何在Python和子进程中使用套接字?

来自分类Dev

Android套接字编程

来自分类Dev

套接字的Android服务

来自分类Dev

Android <-> python套接字

来自分类Dev

Android套接字流

来自分类Dev

使用套接字的IllegalBlockingModeException

来自分类Dev

使用Java套接字发送ByteArray(Android编程)