【问题标题】:Android Studio doInBackground not getting hitAndroid Studio doInBackground 没有被击中
【发布时间】:2018-03-21 16:08:04
【问题描述】:

第一次摆弄 android,我找不到任何解决我的确切问题的方法。尽管这看起来确实是一个常见问题。

当我调试我的应用程序时,它不会进入 downloadTask 活动。

我看到解决方案提到了asyncTask.execute(),但这不起作用。

我有点不知所措。为什么我的应用没有进入doInBackground/downloadTask?

下载任务(doInBackground)

public class DownloadTask extends AsyncTask<String, Void, String>{

@Override
protected String doInBackground(String... urls) {
    String result = "";
    URL url;
    HttpURLConnection urlConnection = null;

    try {
        url = new URL(urls[0]);
        urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = urlConnection.getInputStream();
        InputStreamReader reader = new InputStreamReader(in);
        int data = reader.read();
        while (data!=-1){
            char current = (char) data;
            result += current;
            data = reader.read();
        }

        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

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

    try {
        JSONObject jsonObject = new JSONObject(result);
        Log.d("CREATION", "GOT TO THE FIRST PART");
        JSONObject weatherDatas = new JSONObject(jsonObject.getString("main"));
        Double tempInt = Double.parseDouble(weatherDatas.getString(("temp")));
        int tempIn = (int) (tempInt*1.8-459.67);
        String placeName = jsonObject.getString("name");
        Log.d("CREATION", placeName);
        MainActivity.temperatureTextView.setText(String.valueOf(tempIn)  + "F");
        MainActivity.placeTextView.setText(placeName);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

MainActivity

public class MainActivity extends AppCompatActivity {

static TextView placeTextView;
static TextView temperatureTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    placeTextView = (TextView) findViewById(R.id.nameTextView);

    temperatureTextView = (TextView) findViewById(R.id.temperatureTextView);



    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    String provider = locationManager.getBestProvider(new Criteria(), false);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    Location location = locationManager.getLastKnownLocation(provider);

    Double lat = location.getLatitude();
    Double lng = location.getLongitude();
    DownloadTask task = new DownloadTask();

    task.execute("http://api.openweathermap.org/data/2.5/weather?lat=" +
            String.valueOf(lat) + "&lon=" + String.valueOf(lng) + "&appid=193a308a7dbf9e4d0d8c0b09ff296a88");

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

【问题讨论】:

  • 你调用了task.execute() AsyncTask 应该运行。清单中有INTERNET 权限吗?
  • 你如何检查你没有输入doInBackground?如果放置断点,您可能看不到它中断,因为您在不同的线程中。
  • @ADM 好点。但如果没有 INTERNET 许可,就不会出现异常......
  • 阅读this
  • 是的,我可能会在openConnection() 之后放置断点。而不是在 catch 块中。这只是一个测试用例。 @JoeBoggs 您正在测试哪个 API 版本?

标签: android


【解决方案1】:

我将您的onCreate() 方法更改如下:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    placeTextView = (TextView) findViewById(R.id.nameTextView);

    temperatureTextView = (TextView) findViewById(R.id.temperatureTextView);

    DownloadTask task = new DownloadTask();

    task.execute("http://api.openweathermap.org/data/2.5/weather?lat=" +
            String.valueOf(300) + "&lon=" + String.valueOf(400) + "&appid=193a308a7dbf9e4d0d8c0b09ff296a88");

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

我检查了一下,它输入 doInBackground()(我只是将您的AsyncTask 复制/粘贴到一个新项目中)。不过,我在 API 级别 25 上对其进行了测试。所以我的猜测是您在运行时请求权限有问题,因为您需要在运行时请求 ACCESS_FINE_LOCATION。

因为您没有在运行时请求 ACCESS_FINE_LOCATION,所以权限检查失败并返回。所以你根本不会创建AsyncTask

在此处检查请求权限:Requesting permissions

【讨论】:

  • 我的清单中有 &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt;&lt;uses-permission android:name="android.permission.INTERNET"/&gt;。这还不够吗?如何在运行时访问它?
  • @JoeBoggs 这就是问题所在。对于 INTERNET 权限就足够了,但是对于 ACCESS_FINE_LOCATION,你需要在运行时请求它:developer.android.com/training/permissions/requesting.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多