0
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() 调用同一服务的另一个实例吗?每次连接广播接收器收到连接更改广播时,我可以让服务等待()然后通知()吗?

4

1 回答 1

0

在我看来,实现这种功能的正确方法如下:

  • 如果没有连接 - 放弃Service,注册 aBroadcastReceiver以侦听连接更改并在某处(SharedPreferences例如)保存一个标志,告诉您还有工作要做
  • 当连接建立并且你的标志是true- 重新开始Service并完成工作

希望这可以帮助。

于 2012-07-20T15:02:01.513 回答