【发布时间】:2013-11-27 01:00:34
【问题描述】:
我想用这种方式不断验证Android系统网络,但我认为这种形式不正确,如果wifi或其他网络上的连接可用,我的服务应该更新。
public class ObjService extends Service{
private final static int NOTIFICATION=1;
public static boolean process;
private NotificationManager state;
private NotificationCompat.Builder objBuilder;
public void onCreate(){
process=true;
state=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
objBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.launchimg))
.setSmallIcon(R.drawable.notification_img);
Thread checker=new Thread(){//1
public void run(){//2
while (process){//3
if (verifyConnection()){//4
updateNotificationService("Service is available");
}else{
updateNotificationService("Service is not available");
}//4
try{
Thread.sleep(6000);
}catch(InterruptedException e){
//..printLog..
}
}//3
};//2
};//1
checker.start();
.
.
.
我的函数 verifyConnection() 是:
public boolean verifyConnection() {
boolean flag = true;
ConnectivityManager connec = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] net = connec.getAllNetworkInfo();
if (!net[0].isAvailable() && !net[1].isAvailable())
{
flag = false;
}
return flag;
}
updateNotificationService() 是:
public void updateNotificacionService(String arg){
objBuilder.setContentText(arg)
.setWhen(System.currentTimeMillis());
state.notify(NOTIFICATION, objBuilder.build());
}
【问题讨论】:
-
P.S 如果有错误请见谅。
-
使用this链接检查网络状态
-
使用这个链接-stackoverflow.com/questions/14634074/…希望这对你有帮助!
标签: android networking