本文介绍了我想运行一个后台进程在Android的上网检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要像它在后台运行的异步任务的后台进程。如何运行Internet连接检查作为Android的一个后台进程?

I want a background process like async task which runs in the background. How to run internet connection checking as a background process in Android?

推荐答案

尝试监听通过广播接收器连接状态的变化。

Try to listen for Connectivity State Changes through a Broadcast Receiver.

在清单寄存器接收器:

    <receiver android:name=".MyReceiver">
       <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
       </intent-filter>
    </receiver>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

广播接收器的Java类:

Java class of Broadcast receiver:

public class MyReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
     Log.d("app","Network connectivity change");
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            Log.i("app","Network "+ni.getTypeName()+" connected");
        } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            Log.d("app","There's no network connectivity");
        }
   }
}

这篇关于我想运行一个后台进程在Android的上网检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:40