gpt4 book ai didi

java - 无法在服务中未在 locationManager 上调用 Looper.prepare() 的线程内创建处理程序

转载 作者:行者123 更新时间:2023-11-30 00:49:43 24 4
gpt4 key购买 nike

我是第一次使用位置管理器,我总是遇到同样的错误:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

当我在 locationManager 上调用 .requestLocationUpdates 时会发生这种情况。我不知道如何将它放在主 UI 线程中。这是发生错误的服务的代码:

public class TrackerService extends Service {
private Context mContext;
private LocListener mlocListener;
private LocationManager mlocManager;
private final IBinder myBinder = new MyLocalBinder();

public void initiateTracking() {
this.mContext = getApplicationContext();
mlocManager = (LocationManager) this.mContext.getSystemService(Context.LOCATION_SERVICE);
mlocListener = new LocListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}

public Boolean getGPSStatus(){
return mlocManager.isProviderEnabled(mlocManager.GPS_PROVIDER);
}

public Double[] getCurrentLocation(){
Double[] lonLat = new Double[]{mlocListener.getLon(), mlocListener.getLat()};
Log.d("DEBUG", "getCurrentLocation: " + lonLat);
return lonLat;
}

public class MyLocalBinder extends Binder {
public TrackerService getService() {
return TrackerService.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return myBinder;
}
@Override
public void onCreate()
{
isRunning = true;
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
initiateTracking();
}
}).start();

return Service.START_STICKY;
}
@Override
public void onDestroy() {
isRunning = false;
}
}

以下是我如何启动我的服务然后绑定(bind)到它:

  @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);

startService(new Intent(this, TrackerService.class));
bindService(new Intent(MainActivity.this, TrackerService.class), myConnection, Context.BIND_AUTO_CREATE);
}

最佳答案

您可以像这样添加在主 UI 线程上运行的代码:

runOnUiThread(new Runnable() {
@Override
public void run() {
//your code here
}
});

关于java - 无法在服务中未在 locationManager 上调用 Looper.prepare() 的线程内创建处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41263911/

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