我试图从我的后台线程在 UI 线程上抛出和警告对话框,但我遇到了 runOnUiThread 未定义的问题。我已经尝试过 FindLocation.this.runOnUiThread
和 runOnUiThread 但它们似乎都抛出相同的错误 The method runOnUiThread(new Runnable(){}) is undefined for the type new LocationListener(){}
(或 ...FindLocation 类型
)。任何想法为什么?这是我的 FindLocation.java 类的 fragment 。这是由我的主要 Activity 调用的。
public class FindLocation extends Thread {
public boolean inJurisdiction;
public boolean AlertNotice = false;
private LocationManager locManager;
private LocationListener locListener;
Context ctx;
public String userId;
public FindLocation(Context ctx) {
this.ctx = ctx;
}
public void start(String userId) {
this.userId = userId;
super.start();
}
@Override
public void run() {
Looper.prepare();
final String usr = userId;
//get a reference to the LocationManager
locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location loc) {
String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());
Double latitude = loc.getLatitude();
Double longitude = loc.getLongitude();
if (latitude >= 39.15296 && longitude >= -86.547546 && latitude <= 39.184901 && longitude <= -86.504288 || inJurisdiction != false) {
Log.i("Test", "Yes");
inJurisdiction = true;
FindLocation.this.runOnUiThread(new Runnable() { ///****error here****
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(ctx);
alert.setTitle("Sent");
alert.setMessage("You will be contacted shortly.");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
}
});
最佳答案
由于 runOnUIThread()
是 Activity
的方法,您可以在构造函数中传递对调用 Activity 的引用。
...
Context ctx;
Activity act;
public String userId;
...
public FindLocation(Context ctx, Activity act) {
this.ctx = ctx;
this.act = act;
}
并使用 runOnUIThread()
之类的
act.runOnUiThread(new Runnable() {...});
但是我认为这是不安全的,您需要采取预防措施以确保在调用 runOnUiThread
时您的 Activity 仍然存在
关于java - 未为类定义 runOnUiThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9992060/