gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:35:57 25 4
gpt4 key购买 nike

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

我尝试使用WeakReference,例如:

    private WeakReference<ScanActivity> activityReference;

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

但是 Android Studio 说:

Geocoder (android.content.Context, Locale) in Geocoder cannot be applied to (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);

最佳答案

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

关于java - Android - 静态嵌套类(上下文),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56164669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com