mky*_*ong 14 java multithreading android dialog
我正在尝试从我的后台线程抛出UI警告对话框,但是我遇到了runOnUiThread未定义的问题.我已经尝试过FindLocation.this.runOnUiThread
runOnUiThread,但两者似乎都抛出相同的错误The method runOnUiThread(new Runnable(){}) is undefined for the type new LocationListener(){}
(或...the type FindLocation
).有什么想法吗?这是我的FindLocation.java类的片段.这是我的主要活动.
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) {
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
Vla*_*mir 31
既然runOnUIThread()
是方法Activity
,你可以在构造函数中传递对调用活动的引用.
...
Context ctx;
Activity act;
public String userId;
...
public FindLocation(Context ctx, Activity act) {
this.ctx = ctx;
this.act = act;
}
Run Code Online (Sandbox Code Playgroud)
并使用runOnUIThread()
像
act.runOnUiThread(new Runnable() {...});
Run Code Online (Sandbox Code Playgroud)
但是我认为这是不安全的,你需要采取预防措施,以确保你打电话时你的活动仍在那里 runOnUiThread
Xar*_*mer 13
Another better approach..
Run Code Online (Sandbox Code Playgroud)
无需创建用于获取Activity的构造函数.
只需将上下文强制转换为Activity类.
((Activity)context).runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28671 次 |
最近记录: |