runOnUiThread Undefined for Class

2022-09-03 03:25:01

我正在尝试从后台线程在UI线程上引发并发出警报对话框,但我遇到了runOnUiThread未定义的问题。我已经尝试过并运行OnUiThread,但两者似乎都抛出了相同的错误(或)。任何想法为什么?这是我的FindLocation.java类的一个片段。这是我的主要活动所称呼的。FindLocation.this.runOnUiThreadThe method runOnUiThread(new Runnable(){}) is undefined for the type new LocationListener(){}...the type FindLocation

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) {
                           }
                        });
                    }
                });

答案 1

由于 是 的方法,因此可以在构造函数中传递对调用活动的引用。runOnUIThread()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


答案 2
Another better approach..

无需创建用于获取活动的构造函数。

只需将上下文类型转换为活动类即可。

((Activity)context).runOnUiThread(new Runnable()
    {
        public void run()
        { 
             Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
        }
    });

推荐