2

我想检查后台服务中是否连续存在互联网,以便在设备连接到互联网后立即进行广播。建议一些片段。谢谢你。

4

2 回答 2

3

创建扩展类BroadcastReceiverConnectivityManager.EXTRA_NO_CONNECTIVITY用于获取连接信息。

代码 :

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;

public class CheckConnectivity extends BroadcastReceiver{

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

    boolean isConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    if(isConnected){
        Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
    }
   }
 }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.connect.broadcast"
  android:versionCode="1"
  android:versionName="1.0" >

  <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>

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

  <application
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name" >
       <receiver android:exported="false"
          android:name=".CheckConnectivity" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
     </receiver>
   </application>
</manifest>
于 2013-07-23T06:55:46.013 回答
1

与其创建服务,不如创建具有连接性更改的意图过滤器Developer Android

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

使用您的广播接收器:

public class YourReceiver extends BroadcastReceiver
{
 @Override
 public void onReceive( Context context, Intent intent )
 {

 }
 }
于 2013-07-23T06:56:32.617 回答