即使应用已经关闭,如何继续运行任务?

时间:2015-08-04 11:52:16

标签: android

目前,我已经建立了一个服务,每15秒对我的php服务器进行一次httpRequest。代码运行良好,但问题是当我关闭应用程序时,httpRequest停止工作,不再发送数据。我想要做的是当我关闭应用程序时,httpRequest仍在运行。我的代码应该改变什么?

这是我一直在努力的代码......

public class NotificationService extends Service {

public String response;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "on start command", Toast.LENGTH_SHORT).show();
    new MyAsyncTask().execute("muhammad sappe");
    return START_NOT_STICKY;
}

private class MyAsyncTask extends AsyncTask<String, String, String>{

  @Override
  protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    postData(params[0]);
    return null;
  }

  @Override
  protected void onPostExecute(String result) {
      new Handler().postDelayed(new Runnable() {
            public void run() {
                new MyAsyncTask().execute("muhammad sappe");
            }
        }, 15000);
    super.onPostExecute(result);
  }

}

public void postData(String MyName){
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://mydomain/getData.php");
    try {   
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("action", MyName));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        response = httpclient.execute(httppost, responseHandler);
    }catch(ClientProtocolException e){
        // TODO Auto-generated catch block
    }catch(IOException e) {
        // TODO Auto-generated catch block
    }
}

public void onDestroy() {
    super.onDestroy();
}
}

2 个答案:

答案 0 :(得分:2)

您必须使用前台服务。

前台服务必须有通知,以通知用户即使应用已关闭,仍有服务正在进行。

以下是一个例子:

public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if(intent!=null) {
        if(intent.hasExtra("id")) {
            url = intent.getStringExtra("id");
            int id = 1;
            // Issues the notification
            n = new NotificationCompat.Builder(this).setContentTitle("Workee")
                    .setContentText("Deleting Image")
                    .setProgress(0, 0, true)
                    .setAutoCancel(false)
                    .setSmallIcon(R.drawable.workee_logo).build();
            startForeground(id, n);
            // start thr asnyc task
            deletePhoto();
            return START_STICKY;
        }
    }

答案 1 :(得分:2)

Mariana Itani所述,您需要使用Foreground Service。那是错的!您不需要使用Foreground Service。您需要做的就是改变您的返回值,

来自:

return START_NOT_STICKY;

致:

return START_STICKY;
当您需要显示应用程序在后台执行某项任务的通知时,将使用

Foreground Service。例如,音乐播放器应用程序。