当android杀死后台任务时,AsyncTask postExecute或onCancelled没有被调用 - 没有更多的后台进程

时间:2012-07-31 06:28:57

标签: android android-asynctask

我正在运行一个队列,我正在下载视频和que正常工作,需要获得asyncTask的postExecute,称为mandatorily ..或者必须有一个事件,当我的asynctask被处理器杀死时我可以得到说"没有更多的背景任务" ..内存不足..取消也没有被调用...任何帮助???


@kdehairy意图服务??? Okk实际上我需要更新我的UI ..例如我有一个视频正在下载,从asynctask开始,我跟踪块,并相应更新我的自定义progressBar如果用户销毁活动m不取消我的ansynctask直到我的工作是完成..我跟踪asynctask ..如果由于某种原因我的asynctask停止,即使它在后台...它再次质疑任务...这是由服务完成...即时通讯甚至我不知道我的asynctask是从服务或应用程序排队...但我只是跟踪asyncatsks正在排队..并从堆栈推送和弹出..asynctask postexecute刷新我的视图...就像在asynctask从服务运行我检查postExecute如果我UI屏幕是可见的...而且我调用新的Intent..with Flags SingleTop和New Task,因此我可以刷新我的progressBar ..可以使用IntentService更新我的UI ..它将在UIThread或工作线程上运行.. < / p> 你可以给我一个例子...... ??? 谢谢Kdehairy

2 个答案:

答案 0 :(得分:2)

如果您处理流程的生命周期至关重要,那么最好使用服务。 AsyncTask不是系统组件(服务是)。

更新

  1. 使用您自己的实现扩展IntentService
  2. 更新您可以使用boradcast的UI。如下:

    1. 只要您需要更新自己的用户界面,请在服务中找到:
      
      Intent intent = new Intent(ACTION_UPDATE_PROGRESS);
      intent.putExtra(EXTRA_POSITION, currentValue);
      LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
      
      在这里,我们使用LocalBroadcastManager发送广播,因为我们希望将此广播保持为应用程序的私有。
    2. 您的活动中
    3. 
      // this is the broadcast receiver object that will handle our UI updates.
      private BroadcastReceiver mReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
              int position = intent.getIntExtra(YourService.EXTRA_POSITION, 0);
              // do your UI updates here.
          }
      }
      
      @Override
      protected void onResume() {
          // register for the broadcast.
          LocalBroadcastManager.getInstance(this).registerReceiver(
              mReceiver,
              new IntentFilter(YourService.ACTION_UPDATE_PROGRESS));
          super.onResume();
      }
      @Override
      protected void onPause() {
          // unregister when activity is paused.
          LocalBroadcastManager.getInstance(PlayerActivity.this)
              .unregisterReceiver(mPlayerReceiver);
          super.onPause();
      }
      
  3. 如果您发现任何不清楚的地方,请告知我们。

答案 1 :(得分:0)

尝试这样..或者看看这个例子它可能对你有帮助.. 调用你想要的onCancel()方法..如下面的示例中的Onpause()所示,它将取消asyncTask

public class newA extends Activity implements OnClickListener {

private static final String TAG = "MyPost";

private boolean post_is_running = false;

private doSomethingDelayed doSth;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button pushButton = (Button) findViewById(R.id.push_button);
    pushButton.setOnClickListener(this);

}

@Override
protected void onPause() {
    super.onPause();
    if (post_is_running) {
        Log.v(TAG, "Stopping Async Task onPause");
        doSth.cancel(true);
    }
}

@Override
protected void onResume() {
    super.onResume();
    if (post_is_running) {
        Log.v(TAG, "Starting Async Task onResume");
        doSth = (doSomethingDelayed) new doSomethingDelayed().execute();
        ((Button) findViewById(R.id.push_button)).setText("Resuming..");
    }
}

public void onClick(View v) {
    if (post_is_running == false) {
        post_is_running = true;
        Log.v(TAG, "Starting Async Task onClick");
        doSth = (doSomethingDelayed) new doSomethingDelayed().execute();
        ((Button) findViewById(R.id.push_button)).setText("Starting..");
    } else {
        Log.v(TAG, "Stopping Async Task onClick");
        post_is_running = false;
        doSth.cancel(true);
        ((Button) findViewById(R.id.push_button)).setText("Stopping..");
    }
}

private class doSomethingDelayed extends AsyncTask<Void, Integer, Void> {

    private int num_runs = 0;

    private JSONObject holder;

    @Override
    protected Void doInBackground(Void... gurk) {

        while (!this.isCancelled()) {
            Log.v(TAG, "going into postData");

            long ms_before = SystemClock.uptimeMillis();
            Log.v(TAG, "Time Now is " + ms_before);

            try {
                Thread.sleep(5000);
                postData();

            } catch (InterruptedException e) {

                e.printStackTrace();
            }

            long ms_after = SystemClock.uptimeMillis();

            long time_passed = ms_after - ms_before;

            Log.v(TAG, "coming out of postData");
            Log.i(TAG, "RTT: " + time_passed + " ms");

            num_runs++;

            if (!this.isCancelled()) {
                publishProgress(num_runs, (int) time_passed);
            }

        }
        return null;
    }

    @Override
    protected void onCancelled() {
        Context context = getApplicationContext();
        CharSequence text = "request is send every 5 sec.";
        int duration = Toast.LENGTH_LONG;

        Toast.makeText(context, text, duration).show();

        ((Button) findViewById(R.id.push_button))
                .setText("Stopped. Tap to Start for sending new request!");
    }

    @Override
    protected void onProgressUpdate(Integer... num_runs) {
        Context context = getApplicationContext();
        CharSequence text = "Looped with time interval in every 5 sec "
                + num_runs[0].toString() + " Times";
        int duration = Toast.LENGTH_SHORT;

        Toast.makeText(context,
                text + "\nRTT: " + num_runs[1].toString() + " ms", duration)
                .show();

        ((Button) findViewById(R.id.push_button)).setText(text
                + "\nTap to Stop process");

    }

    public void postData() {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.1/listen");

        String resp = null;
        long time_passed = 0;

        // Sending details in Json Format

        holder = new JSONObject();

        try {
            holder.put("UserId", "1");
            holder.put("TimeStamp", "12345");
            System.out.println("----holder--" + holder);

        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        try {
            StringEntity se = new StringEntity(holder.toString());
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            httppost.setEntity(se);
            HttpResponse response = httpclient.execute(httppost);
            resp = response.toString();
            String t = EntityUtils.toString(response.getEntity());

        } catch (ClientProtocolException e) {
            Log.e(TAG, e.toString());
        } catch (IOException e) {
            Log.e(TAG, e.toString());
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        Log.i(TAG, "RTT inside post-data: " + time_passed);

        Log.i(TAG, resp.toString());
    }
}
}