publicclassHeartbeatServiceextendsServiceimplementsRunnable
{
privateThread mThread;
publicintcount =0;
privatebooleanisTip =true;
privatestaticString mRestMsg;
privatestaticString KEY_REST_MSG ="KEY_REST_MSG";
@Override
publicvoidrun()
{
while(true)
{
try
{
if(count >1)
{
Log.i("@qi","offline");
count = 1;
if(isTip)
{
//判断应用是否在运行
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List list = am.getRunningTasks(3);
for(RunningTaskInfo info : list)
{
if(info.topActivity.getPackageName().equals("org.yhn.demo"))
{
//通知应用,显示提示“连接不到服务器”
Intent intent = newIntent("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();
}
}
}
privatevoidsendHeartbeatPackage(String msg)
{
HttpGet httpGet = newHttpGet(msg);
DefaultHttpClient httpClient = newDefaultHttpClient();
// 发送请求
HttpResponse httpResponse = null;
try
{
httpResponse = httpClient.execute(httpGet);
}
catch(Exception e)
{
e.printStackTrace();
}
if(httpResponse ==null)
{
return;
}
// 处理返回结果
finalintresponseCode = httpResponse.getStatusLine().getStatusCode();
if(responseCode == HttpStatus.SC_OK)
{
//只要服务器有回应就OK
count = 0;
isTip = true;
}
else
{
Log.i("@qi","responseCode "+ responseCode);
}
}
@Override
publicIBinder onBind(Intent intent)
{
returnnull;
}
@Override
publicvoidonCreate()
{
super.onCreate();
}
@Override
publicvoidonDestroy()
{
super.onDestroy();
}
publicvoidonStart(Intent intent,intstartId)
{
Log.i("@qi","service onStart");
//从本地读取服务器的URL,如果没有就用传进来的URL
mRestMsg = getRestMsg();
if(mRestMsg ==null|| mRestMsg =="")
{
mRestMsg = intent.getExtras().getString("url");
}
setRestMsg(mRestMsg);
mThread = newThread(this);
mThread.start();
count = 0;
super.onStart(intent, startId);
}
publicString getRestMsg()
{
SharedPreferences prefer = getSharedPreferences("settings.data", Context.MODE_PRIVATE);
Log.i("@qi","getRestMsg() "+ prefer.getString(KEY_REST_MSG,""));
returnprefer.getString(KEY_REST_MSG,"");
}
publicvoidsetRestMsg(String restMsg)
{
SharedPreferences prefer = getSharedPreferences("settings.data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefer.edit();
editor.putString(KEY_REST_MSG, restMsg);
editor.commit();
}
}