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
}
}
what if there’s still no internet conectivity? Should i just call another instance of the same service from the broadcast receiver instead of fb_post()? Can I make a service wait() and then notify() every time a connectivity broadcast receiver recieves a connection change broadcast?
In my opinion the right way to implement this kind of functionality is as follows:
Service, register aBroadcastReceiverto listen for connection changes and save a flag somewhere (SharedPreferencesfor example) telling that there is work left to dotrue– start theServiceagain and do the jobHope this helps.