1

我正在运行一个队列,我正在下载视频,并且为了让 que 正常工作,需要强制调用 AsyncTask 的 postExecute ..或者当我的 asynctask 被处理器杀死时,我必须有一个事件,它说“不”更多后台任务”..内存不足..OnCancelled 也没有被调用...任何帮助???


@kdehairy 意向服务???好的,实际上我需要更新我的 UI ..例如,我正在下载一个在 asynctask 中开始的视频,我会跟踪该块并相应地更新我的自定义进度条,如果用户破坏了活动 m 直到我的工作才取消我的 ansynctask完成..我跟踪异步任务..如果由于某种原因我的异步任务停止,即使它在后台......它再次询问任务..这是由服务完成的......我说的是即使我不知道我的异步任务从服务或应用程序排队...但我只是跟踪正在排队的 asyncatsks..并从堆栈中推送和弹出..asynctask postexecute 刷新我的视图...如果 asynctask 正在从服务运行我检查 postExecute 如果我的UI 屏幕是可见的......比我调用新的 Intent..with Flags SingleTop 和 New Task ,因此我可以刷新我的progressBar ..

你能给我举个例子吗……???谢谢 Kdehairy

4

2 回答 2

2

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

更新:

  1. IntentService用你自己的实现扩展。
  2. 要更新 UI,您可以使用广播。如下:

    1. 每当您需要更新 UI 时,将其写入您的服务中:
      
      Intent intent = new Intent(ACTION_UPDATE_PROGRESS);
      intent.putExtra(EXTRA_POSITION, currentValue);
      LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
      
      在这里,我们使用 发送广播,LocalBroadcastManager因为我们希望将此广播保密给应用程序。
    2. 在您的活动中:

      
      // 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();
      }
      

如果您发现任何不清楚的地方,请告诉我。

于 2012-08-03T00:42:21.170 回答
0

try like this.. or look at this example it migth help you.. call onCancle() method where you want.. as shown in Onpause() in below example, It ll cancel the 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());
    }
}
}
于 2012-09-28T07:46:08.890 回答