java - 未为类定义 runOnUiThread

标签 java android multithreading dialog

我试图从我的后台线程在 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/

相关文章:

java - 使用 pmap 和 gdb 查找 native 内存泄漏

Android:如何从设计中计算 dpi?

java - 当您更改 xml 文件中的属性时,会调用自定义 View 的哪个构造函数?

java - 为什么我们应该在 try block 中使用 wait() 方法?我们可以在 try block 之外使用 wait() 方法吗?

java - ConcurrentHashMap迭代保证

java - WAIT 和 BLOCKED 线程状态之间的区别

java - ActionListener 在按钮单击时不执行任何操作

java - Android:仅使用 GCM 的 TCP/IP-Server

java - org.springframework.mapping