Android-静态嵌套类(上下文)

时间:2019-05-16 08:58:23

标签: java android android-asynctask android-context weak-references

我有一个静态AsyncTask,我需要获取上下文,该怎么做?

我尝试使用WeakReference,例如:

    private WeakReference<ScanActivity> activityReference;

    FetchPositionAsyncTask(ScanActivity context) {
        activityReference = new WeakReference<>(context);
    }

但是Android Studio说:

  

Geocoder中的Geocoder(android.content.Context,Locale)无法应用于(java.lang.ref.WeakReference,Locale)

这是我的代码:

private static class FetchPositionAsyncTask extends AsyncTask<String, Void, String> {

    private WeakReference<ScanActivity> activityReference;

    FetchPositionAsyncTask(ScanActivity context) {
        activityReference = new WeakReference<>(context);
    }

    @Override
    protected String doInBackground(String... params) {
        return null;
    }

    protected void onPostExecute(String result) {
        //TODO da mettere in doInBackground

        final AlertDialog.Builder builder;

        //GET ADDRESS FROM COORDINATES
        Geocoder geocoder = new Geocoder(activityReference, Locale.getDefault());
        try {
            DATA_LOCALITY = geocoder.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String DATA_ADDRESS = DATA_LOCALITY.get(0).getAddressLine(0);


        //TEST
        builder = new AlertDialog.Builder(activityReference.this);
        builder.setTitle("").setMessage("Latitude: " + latitude + " " + "Longitude: " + longitude + " " + "Accuracy: " + accuracy + " " + "Address: " + DATA_ADDRESS).setNeutralButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show().setCanceledOnTouchOutside(false);
    }
}

这是我设置代码的方式:

Geocoder geocoder = new Geocoder(activityReference, Locale.getDefault());

builder = new AlertDialog.Builder(activityReference);

2 个答案:

答案 0 :(得分:0)

您需要使用activityReference.get()来使用参考变量中的Context

答案 1 :(得分:0)

function concat([...arr1], arr2, atIndex){ arr1.splice(atIndex, 0, ...arr2); return arr1; } var arr1 = ["a","b","c"], arr2 = ["1","2","3"]; console.log(...concat(arr1, arr2, 2)); // ["a", "b", "1", "2", "3", "c"] console.log(...concat(arr1, arr2, 0)); // ["1", "2", "3", "a", "b", "c"]WeakReference<ScanActivity>不同,您应该使用ScanActivity使用真实对象并将其传递给activityReference.get()。即

Geocoder