Android 後台Service : 向伺服器發送心跳包

來源:互聯網
上載者:User

[java] public class HeartbeatService extends Service implements Runnable  {      private Thread          mThread;      public int              count           = 0;      private boolean         isTip           = true;      private static String   mRestMsg;      private static String   KEY_REST_MSG    = "KEY_REST_MSG";        @Override      public void run()      {          while (true)          {              try              {                  if (count > 1)                  {                      Log.i("@qi", "offline");                      count = 1;                      if (isTip)                      {                          //判斷應用是否在運行                           ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);                          List<RunningTaskInfo> list = am.getRunningTasks(3);                          for (RunningTaskInfo info : list)                          {                              if (info.topActivity.getPackageName().equals("org.yhn.demo"))                              {                                  //通知應用,顯示提示“串連不到伺服器”                                   Intent intent = new Intent("org.yhn.demo");                                  intent.putExtra("msg", true);                                  sendBroadcast(intent);                                  break;                              }                          }                            isTip = false;                      }                  }                  if (mRestMsg != "" && mRestMsg != null)                  {                      //向伺服器發送心跳包                       sendHeartbeatPackage(mRestMsg);                      count += 1;                  }                    Thread.sleep(1000 * 3);              }              catch (InterruptedException e)              {                  e.printStackTrace();              }          }      }        private void sendHeartbeatPackage(String msg)      {          HttpGet httpGet = new HttpGet(msg);          DefaultHttpClient httpClient = new DefaultHttpClient();          // 發送請求           HttpResponse httpResponse = null;          try          {              httpResponse = httpClient.execute(httpGet);          }          catch (Exception e)          {              e.printStackTrace();          }          if (httpResponse == null)          {              return;          }            // 處理返回結果           final int responseCode = httpResponse.getStatusLine().getStatusCode();          if (responseCode == HttpStatus.SC_OK)          {              //只要伺服器有回應就OK               count = 0;              isTip = true;          }          else          {              Log.i("@qi", "responseCode " + responseCode);          }        }        @Override      public IBinder onBind(Intent intent)      {          return null;      }          @Override      public void onCreate()      {          super.onCreate();      }            @Override      public void onDestroy()      {          super.onDestroy();      }        public void onStart(Intent intent, int startId)      {          Log.i("@qi", "service onStart");          //從本地讀取伺服器的URL,如果沒有就用傳進來的URL           mRestMsg = getRestMsg();          if (mRestMsg == null || mRestMsg == "")          {              mRestMsg = intent.getExtras().getString("url");          }          setRestMsg(mRestMsg);            mThread = new Thread(this);          mThread.start();          count = 0;            super.onStart(intent, startId);      }        public String getRestMsg()      {          SharedPreferences prefer = getSharedPreferences("settings.data", Context.MODE_PRIVATE);          Log.i("@qi", "getRestMsg() " + prefer.getString(KEY_REST_MSG, ""));          return prefer.getString(KEY_REST_MSG, "");      }        public void setRestMsg(String restMsg)      {          SharedPreferences prefer = getSharedPreferences("settings.data", Context.MODE_PRIVATE);          SharedPreferences.Editor editor = prefer.edit();          editor.putString(KEY_REST_MSG, restMsg);          editor.commit();      }    }   public class HeartbeatService extends Service implements Runnable{private Thread mThread;public int count = 0;private boolean isTip = true;private static String mRestMsg;private static String KEY_REST_MSG = "KEY_REST_MSG"; @Overridepublic void run(){while (true){try{if (count > 1){Log.i("@qi", "offline");count = 1;if (isTip){//判斷應用是否在運行ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);List<RunningTaskInfo> list = am.getRunningTasks(3);for (RunningTaskInfo info : list){if (info.topActivity.getPackageName().equals("org.yhn.demo")){//通知應用,顯示提示“串連不到伺服器”Intent intent = new Intent("org.yhn.demo");intent.putExtra("msg", true);sendBroadcast(intent);break;}} isTip = false;}}if (mRestMsg != "" && mRestMsg != null){//向伺服器發送心跳包sendHeartbeatPackage(mRestMsg);count += 1;} Thread.sleep(1000 * 3);}catch (InterruptedException e){e.printStackTrace();}}} private void sendHeartbeatPackage(String msg){HttpGet httpGet = new HttpGet(msg);DefaultHttpClient httpClient = new DefaultHttpClient();// 發送請求HttpResponse httpResponse = null;try{httpResponse = httpClient.execute(httpGet);}catch (Exception e){e.printStackTrace();}if (httpResponse == null){return;} // 處理返回結果final int responseCode = httpResponse.getStatusLine().getStatusCode();if (responseCode == HttpStatus.SC_OK){//只要伺服器有回應就OKcount = 0;isTip = true;}else{Log.i("@qi", "responseCode " + responseCode);} } @Overridepublic IBinder onBind(Intent intent){return null;}  @Overridepublic void onCreate(){super.onCreate();}   @Overridepublic void onDestroy(){super.onDestroy();} public void onStart(Intent intent, int startId){Log.i("@qi", "service onStart");//從本地讀取伺服器的URL,如果沒有就用傳進來的URLmRestMsg = getRestMsg();if (mRestMsg == null || mRestMsg == ""){mRestMsg = intent.getExtras().getString("url");}setRestMsg(mRestMsg); mThread = new Thread(this);mThread.start();count = 0; super.onStart(intent, startId);} public String getRestMsg(){SharedPreferences prefer = getSharedPreferences("settings.data", Context.MODE_PRIVATE);Log.i("@qi", "getRestMsg() " + prefer.getString(KEY_REST_MSG, ""));return prefer.getString(KEY_REST_MSG, "");} public void setRestMsg(String restMsg){SharedPreferences prefer = getSharedPreferences("settings.data", Context.MODE_PRIVATE);SharedPreferences.Editor editor = prefer.edit();editor.putString(KEY_REST_MSG, restMsg);editor.commit();} }  啟動Service:  [java]  Intent serviceIntent = new Intent("HeartbeatService");  serviceIntent.putExtra("url",url);  startService(serviceIntent);   Intent serviceIntent = new Intent("HeartbeatService");serviceIntent.putExtra("url",url);startService(serviceIntent);    最後別忘了註冊Server和GET_TASKS  [html]  <service              android:name=".demo.HeartbeatService"              android:label="QServer"              android:persistent="true" >              <intent-filter>                  <action android:name="HeartbeatService" />              </intent-filter>          </service>   <service            android:name=".demo.HeartbeatService"            android:label="QServer"            android:persistent="true" >            <intent-filter>                <action android:name="HeartbeatService" />            </intent-filter>        </service>[html] view plaincopyprint?<uses-permission android:name="android.permission.GET_TASKS" />   <uses-permission android:name="android.permission.GET_TASKS" />   運行效果:    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.