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

时间:2016-12-21 13:28:29

标签: java android multithreading locationmanager

我是第一次与位置管理员合作,我总是得到同样的错误:

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

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

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

1 个答案:

答案 0 :(得分:1)

您可以添加代码以在主UI线程上运行,如下所示:

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