【问题标题】:Can't make Asynctask work for different android versions无法使 Asynctask 适用于不同的 android 版本
【发布时间】:2015-10-06 02:38:16
【问题描述】:

我正在使用此代码:

  public void run() {
        handler.post(new Runnable() {
            public void run() {       
                try {
                    if (count==true)
                    {        
                        try 
                        {
                            r.stop();
                        } catch (Exception e) {}
                        tranca=false;
                        count=false; 

                        dlg.dismiss();
                        dlg.cancel();
                        dlg.dismiss();

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                            new AsyncCaller().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );
                             //task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
                        } else {
                            new AsyncCaller().execute();
                        }
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                }
            }
        });
    }
}, 15000);

问题是我不知道怎么做 新的 AsyncCaller().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );

工作。问题是 asynctask 在蜂窝之后改变了它的工作方式,我找到了这段代码。它适用于 Honeycomb 以下的 Android 版本,但在我的 jellybean 中它不起作用。我可能正在使用 new AsyncCaller().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR ); 以错误的方式。 异步任务是这样的:

private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
    public JSONObject getLocationInfo() {

        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+latitude1+","+longitude2+"&sensor=true");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
            } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.show();
    }
    @Override
    protected Void doInBackground(Void... params) {

        //this method will be running on background thread so don't update UI frome here
        //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here


        JSONObject ret = getLocationInfo(); 
        JSONObject location2;
        String location_string;
        try {
            location2 = ret.getJSONArray("results").getJSONObject(0);
            location_string = location2.getString("formatted_address");
            Log.d("test", "formattted address:" + location_string);
            StringRua = (" " + location_string);
        } catch (JSONException e1) {
            e1.printStackTrace();

        }

         StringSMS = (" Latitude " + StringLat + " Longitude " + StringLon + " Ad " + StringRua);   




        EditText Search01; 
        String String01;

        Search01 = (EditText) findViewById(R.id.Search01);
        String01 = Search01.getText().toString();  


        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(String01, null, StringSMS , null, null);

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        //this method will be running on UI thread

        pdLoading.dismiss();
    }

    }   

我知道 stackoverflow 中有同样的问题,但我尝试了很多解决方案,但似乎没有人适合我。我只需要为 JellyBean 设备适当地调用 asynctask。请记住,new AsyncCaller().execute(); 在蜂窝以下的设备中完美运行。 谢谢你

编辑:仍然不工作,它不执行果冻豆设备中 dointhebackground 中的内容(它显示加载,所以我知道它发送到 AsynctTask)。我已经尝试将在 Pre 和 Post 中需要做的事情放在 dothebackground 之外,但由于“NetworkOnMainThreadException”问题,我不能这样做,这只是在新的 android 版本上强制关闭程序。

【问题讨论】:

  • 你的 minSdk 和 targetSdk 是什么?
  • android:minSdkVersion="8" android:targetSdkVersion="11"
  • 在下面查看我的答案
  • 所以不要试图拖钓,而是定义“不工作”。您正在从不是 UI 线程的线程上的屏幕组件中读取数据。所以我猜你正在阅读的数字是空的,并且 doInBackground 是没有操作的。为什么不让 AsyncCaller 成为 AsyncCaller 并实际定义广播的pendingIntent。这样你就可以在 UI 线程上执行 executeOnExecutor(executor, String.valueOf(textView.getText()); 并且成功将被广播。

标签: android android-asynctask versions


【解决方案1】:

如果您想在不同的线程池执行器上执行异步任务,请在此处复制异步任务代码 https://stackoverflow.com/a/9509184/2190244 并通过调用 execute 将其用于 HC 前和后 HC。对于 HC 及以上的 AsyncTasks,使用的内部方法是串行执行器,除非您指定自己的执行器并将其传递给执行方法。

如果你不想使用该代码,你仍然可以为pre和post HC调用execute,它应该可以正常工作

【讨论】:

    【解决方案2】:

    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB), 在此处删除 =。如果您的 BuildVersion 是 api 11,那么它已经可以串行运行了。

    尝试将您的 targetSdk 更改为最新版本。 AsyncTask 的处理方式(串行/并行)取决于 targetSdk。阅读更多关于 AsyncTask 的陷阱here

    【讨论】:

    • 显然它适用于我的 ICS 设备(这也不起作用)。果冻豆手机是我朋友的手机,他不在这里,知道,但稍后他会测试它,我会把结果放在这里,如果工作我接受这个作为答案。谢谢
    • 不。不工作,他对其进行了测试,它进行了加载,但它不执行 dointhebackground 内部的内容。我已经尝试将需要做的事情放在doingthebackground之外,但由于“NetworkOnMainThreadException”问题,我不能这样做,这只是在新的android版本上强制关闭程序。
    • 是的,当然,你永远不能在主线程上运行网络代码。从更高版本之一开始,它会引发错误以避免开发人员这样做。你必须确保你所有的网络代码都在另一个线程中运行(doInBackground,或者只是一个新线程)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    相关资源
    最近更新 更多