Android 后台Service : 向服务器发送心跳包

来源:互联网 发布:淘宝助理5系列教程 编辑:程序博客网 时间:2024/05/06 03:10

[java] view plaincopyprint?
  1. public class HeartbeatService extends Service implements Runnable  
  2. {  
  3.     private Thread          mThread;  
  4.     public int              count           = 0;  
  5.     private boolean         isTip           = true;  
  6.     private static String   mRestMsg;  
  7.     private static String   KEY_REST_MSG    = "KEY_REST_MSG";  
  8.   
  9.     @Override  
  10.     public void run()  
  11.     {  
  12.         while (true)  
  13.         {  
  14.             try  
  15.             {  
  16.                 if (count > 1)  
  17.                 {  
  18.                     Log.i("@qi""offline");  
  19.                     count = 1;  
  20.                     if (isTip)  
  21.                     {  
  22.                         //判断应用是否在运行  
  23.                         ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);  
  24.                         List<RunningTaskInfo> list = am.getRunningTasks(3);  
  25.                         for (RunningTaskInfo info : list)  
  26.                         {  
  27.                             if (info.topActivity.getPackageName().equals("org.yhn.demo"))  
  28.                             {  
  29.                                 //通知应用,显示提示“连接不到服务器”  
  30.                                 Intent intent = new Intent("org.yhn.demo");  
  31.                                 intent.putExtra("msg"true);  
  32.                                 sendBroadcast(intent);  
  33.                                 break;  
  34.                             }  
  35.                         }  
  36.   
  37.                         isTip = false;  
  38.                     }  
  39.                 }  
  40.                 if (mRestMsg != "" && mRestMsg != null)  
  41.                 {  
  42.                     //向服务器发送心跳包  
  43.                     sendHeartbeatPackage(mRestMsg);  
  44.                     count += 1;  
  45.                 }  
  46.   
  47.                 Thread.sleep(1000 * 3);  
  48.             }  
  49.             catch (InterruptedException e)  
  50.             {  
  51.                 e.printStackTrace();  
  52.             }  
  53.         }  
  54.     }  
  55.   
  56.     private void sendHeartbeatPackage(String msg)  
  57.     {  
  58.         HttpGet httpGet = new HttpGet(msg);  
  59.         DefaultHttpClient httpClient = new DefaultHttpClient();  
  60.         // 发送请求  
  61.         HttpResponse httpResponse = null;  
  62.         try  
  63.         {  
  64.             httpResponse = httpClient.execute(httpGet);  
  65.         }  
  66.         catch (Exception e)  
  67.         {  
  68.             e.printStackTrace();  
  69.         }  
  70.         if (httpResponse == null)  
  71.         {  
  72.             return;  
  73.         }  
  74.   
  75.         // 处理返回结果  
  76.         final int responseCode = httpResponse.getStatusLine().getStatusCode();  
  77.         if (responseCode == HttpStatus.SC_OK)  
  78.         {  
  79.             //只要服务器有回应就OK  
  80.             count = 0;  
  81.             isTip = true;  
  82.         }  
  83.         else  
  84.         {  
  85.             Log.i("@qi""responseCode " + responseCode);  
  86.         }  
  87.   
  88.     }  
  89.   
  90.     @Override  
  91.     public IBinder onBind(Intent intent)  
  92.     {  
  93.         return null;  
  94.     }  
  95.   
  96.   
  97.     @Override  
  98.     public void onCreate()  
  99.     {  
  100.         super.onCreate();  
  101.     }  
  102.   
  103.   
  104.   
  105.     @Override  
  106.     public void onDestroy()  
  107.     {  
  108.         super.onDestroy();  
  109.     }  
  110.   
  111.     public void onStart(Intent intent, int startId)  
  112.     {  
  113.         Log.i("@qi""service onStart");  
  114.         //从本地读取服务器的URL,如果没有就用传进来的URL  
  115.         mRestMsg = getRestMsg();  
  116.         if (mRestMsg == null || mRestMsg == "")  
  117.         {  
  118.             mRestMsg = intent.getExtras().getString("url");  
  119.         }  
  120.         setRestMsg(mRestMsg);  
  121.   
  122.         mThread = new Thread(this);  
  123.         mThread.start();  
  124.         count = 0;  
  125.   
  126.         super.onStart(intent, startId);  
  127.     }  
  128.   
  129.     public String getRestMsg()  
  130.     {  
  131.         SharedPreferences prefer = getSharedPreferences("settings.data", Context.MODE_PRIVATE);  
  132.         Log.i("@qi""getRestMsg() " + prefer.getString(KEY_REST_MSG, ""));  
  133.         return prefer.getString(KEY_REST_MSG, "");  
  134.     }  
  135.   
  136.     public void setRestMsg(String restMsg)  
  137.     {  
  138.         SharedPreferences prefer = getSharedPreferences("settings.data", Context.MODE_PRIVATE);  
  139.         SharedPreferences.Editor editor = prefer.edit();  
  140.         editor.putString(KEY_REST_MSG, restMsg);  
  141.         editor.commit();  
  142.     }  
  143.   
  144. }  


启动Service:

[java] view plaincopyprint?
  1. Intent serviceIntent = new Intent("HeartbeatService");  
  2. serviceIntent.putExtra("url",url);  
  3. startService(serviceIntent);  


最后别忘了注册Server和GET_TASKS

[html] view plaincopyprint?
  1. <service  
  2.             android:name=".demo.HeartbeatService"  
  3.             android:label="QServer"  
  4.             android:persistent="true" >  
  5.             <intent-filter>  
  6.                 <action android:name="HeartbeatService" />  
  7.             </intent-filter>  
  8.         </service>  
[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.GET_TASKS" />  


运行效果:

来源:http://blog.csdn.net/vestigge/article/details/8563447

原创粉丝点击