public class FBPost extends Service{
private Bundle params = new Bundle();
private String userID="";
String response;
public void onCreate(String userID,String name)
{
super.onCreate();
params.putString("message", "Test " + new Date().toLocaleString() );
params.putString("caption", "Hey there");
this.userID=userID;
}
@Override
public int onStartCommand( Intent intent , int flags , int startId )
{
if(checkInternetConnection())
{
fb_post();
return 0;
}
else
{
BroadcastReceiver connec_recv= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(checkInternetConnection())
fb_post();
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connec_recv, intentFilter);
}
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
try{
URL url = new URL("http://www.google.com");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.close();
return true;
} catch (Exception e) {
return false;
}
}
return false;
}
private void fb_post()
{
//MORE CODE
}
}
如果仍然没有互联网连接怎么办?我应该从广播接收器而不是 fb_post() 调用同一服务的另一个实例吗?每次连接广播接收器收到连接更改广播时,我可以让服务等待()然后通知()吗?