|
问一下如何在service里判断网络是否连接?由于service的生命周期比receiver长,所以在receiver中只是接收一下,我的receiver代码如下:public class NetConn extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
Toast.makeText(context, "OK,the net has been connected", Toast.LENGTH_LONG);
}else {
Toast.makeText(context, "error", Toast.LENGTH_LONG);
}
}else {
Toast.makeText(context, "error", Toast.LENGTH_LONG);
}
}
public static boolean checkNetConn(Context context)
{
try {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static BitmapDrawable getImageFromURL(URL url)
{BitmapDrawable bd=null;
try{
//创建连接
HttpURLConnection hc=(HttpURLConnection)url.openConnection();
//获取数据
bd=new BitmapDrawable(hc.getInputStream());
//关闭连接
hc.disconnect();
}catch(Exception e){}
return bd;
}
这个代码如何在activity中调用以及在service里进行监听,请教一下高手们!!谢谢了 |
|