1
我開發Android應用程序使用GCM,我想每5分鐘發送一次心跳,我創建運行服務時,這些都是我的代碼,發送心跳gcm?
public class sendHeartbeat extends Service{
private Handler customHandler = new Handler();
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "onStart");
customHandler.postDelayed(updateTimerThread, 0);
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
}
private Runnable updateTimerThread = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
new syncGetHeartbeat().execute();
Log.d("send hearbeat","send hearrrrrrrbeat");
customHandler.postDelayed(this, 260000);
}
};
class syncGetHeartbeat extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... unsued) {
try {
String varId="naengoland";
String url = "http://mydomain.com/gcmserver/getHeartbeat.php?id="+varId;
getRequestJSON(url);
return null;
} catch (Exception e) {
Log.e(e.getClass().getName(), "service get hertbeat "+ e.toString());
return null;
}
}
@Override
protected void onProgressUpdate(Void... unsued) {
}
@Override
protected void onPostExecute(String sResponse) {
}
}
public String getRequestJSON(String Url){
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
client.execute(request);
}catch(Exception ex){
}
return null;
}
}
我成功地發送了心跳每5分鐘,但問題是我的應用程序運行緩慢並消耗很多電量,有沒有什麼方法可以在我的方式旁邊發送心跳? 我的意思是,比我的方法更好的方法。
請幫忙。