我想在后台服务中检查互联网是否存在,以便在设备连接到互联网后立即进行广播。建议一些片段。谢谢。
答案 0 :(得分:3)
创建扩展BroadcastReceiver
的类,使用ConnectivityManager.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>
答案 1 :(得分:1)
而不是创建服务只是创建具有连接性更改{} 3}}
的intent-filter<receiver android:enabled="true" android:name=".YourReceiver"
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
使用您的BroadcastReciever:
public class YourReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
}
}