我知道很多人会发现这个问题不值得,但我是Android开发的新手。我想了解服务和广播接收器。我在广播接收器上看了一些演示应用程序并制作了很少的演示应用程序。现在我在尝试完成我需要帮助。 我想创建一个在后台运行的服务,它会告诉用户有关网络或无线网络的可用性。请帮帮我。谢谢
答案 0 :(得分:0)
您可以使用广播接收器
<receiver
android:name=".NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
在您的Receiver类
中public class NetworkChangeReceiver extends BroadcastReceiver {
public static Internet internet;
public static String changestatus = "";
@Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
if (status.equals("Not connected to Internet")) {
if (context != null && internet != null) {
internet.net();
}
}
changestatus = status;
}
public interface Internet {
public void net();
}
}
Network Util类检查连接性
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
if (context==null) {
return 0;
}
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
在您的活动中,您可以实现网络接口
public class MyActivity extends FragmentActivity implements
Internet {
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
NetworkChangeReceiver.internet = this;
}
@Override
public void net() {
// TODO Auto-generated method stub
//Show Alert connection is not avaiable
}
}
答案 1 :(得分:-1)
堆栈溢出和其他站点有很多可用的解决方案。其中一个很好的解决方案是here ..