gpt4 book ai didi

android - 在 android 上检查与服务的互联网连接

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:38 25 4
gpt4 key购买 nike

我知道如何使用 Activity 打开我的应用程序时检查互联网连接。但是当我的应用程序未运行时如何检查服务中的连接?

最佳答案

您可能需要使用广播接收器。您将不断收到连接更新。(连接/断开连接)

例子:

list :

权限:

    <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

注册广播接收器:

<receiver android:name=".ConnectivityChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

创建接收器类:

public class ConnectivityChangeReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {

// Explicitly specify that which service class will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
YourService.class.getName());
intent.putExtra("isNetworkConnected",isConnected(context));
startService(context, (intent.setComponent(comp)));
}

public boolean isConnected(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}

}

您的服务等级:

class YourService extends IntentService{

@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
boolean isNetworkConnected = extras.getBoolean("isNetworkConnected");
// your code

}

}

关于android - 在 android 上检查与服务的互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com