位置监听器 - 不是从服务启动,而是从活动开始

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了位置监听器 - 不是从服务启动,而是从活动开始相关的知识,希望对你有一定的参考价值。

我正在尝试从服务调用LocationListener类,但似乎侦听器无法启动。当我从一个Activity中调用它时它运行良好。当我尝试相同(只删除“this”参数)时,它不起作用。

上下文参数似乎有问题,但我不知道如何解决它。

从活动呼叫(工作):

LocationTest2 locationListener = new LocationTest2(getApplicationContext());
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

从服务呼叫(不工作):

LocationTest2 locationListener = new LocationTest2(getApplicationContext());
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

分类:LocationTest2:

public class LocationTest2 extends Thread implements LocationListener {
private String TAG = "LocationTest2";
private Context context;
private boolean isOnline = false;

private LocationManager locationManager;

public LocationTest2(Context context) {
    LogSys.e(TAG, "Serviço criado!");
    this.context = context;
}


public void startListening() {
    isOnline = true;
    LogSys.e(TAG, "Ligando serviço");
    Toast.makeText(context, "Ligando serviço!", Toast.LENGTH_SHORT).show();
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}

public void stopListening() {
    if(locationManager != null)
    {
        Toast.makeText(context, "Desligando serviço!", Toast.LENGTH_SHORT).show();
        locationManager.removeUpdates(this);
    }
    isOnline = false;
}

public boolean isOnline()
{
    return isOnline;

}
//=================================

@Override
public void onLocationChanged(Location location) {
    String locationStr = "LOCATION WORKED 33!!! " + location.getLatitude() + " | " + location.getLongitude();
    LogSys.e(TAG, locationStr);
    Toast.makeText(context, locationStr, Toast.LENGTH_SHORT).show();

    setLocationToFirebase(location);
}

public void setLocationToFirebase(Location location)
{
    String tbl_cliente = GlobalVars.SQL_TABELA_CLIENTE_DEVICE_NAME;
    String tbl_dispositivo = GlobalVars.SQL_TABELA_DISPOSITIVO_NAME;
    String tbl_coordinates = GlobalVars.SQL_TABELA_COORDINATES_NAME;

    DatabaseReference databaseReference;
    FirebaseDatabase firebaseDatabase;

    firebaseDatabase = FirebaseDatabase.getInstance();
    try {
        firebaseDatabase.setPersistenceEnabled(true);
    }catch(DatabaseException e){
        LogSys.e(TAG, "DatabaseException: " + e.getMessage());
    }
    databaseReference = firebaseDatabase.getReference();

    Cliente clienteSQLite = Cliente.getClienteSQLite(context);
    Dispositivo dispositivoSQLite = Dispositivo.getDispositivoSQLite(context);

    DatabaseReference dbRef = databaseReference.child(tbl_cliente)
            .child(clienteSQLite.getId())
            .child(tbl_dispositivo)
            .child(dispositivoSQLite.getId())
            .child(tbl_coordinates).push();
    String key = dbRef.getKey();

    Coordenadas coords = new Coordenadas();
    coords.setId(key);
    coords.setLatitude(location.getLatitude());
    coords.setLongitude(location.getLongitude());
    coords.setData(DataHoraAtual.getData());
    coords.setHora(DataHoraAtual.getHora());

    dbRef.setValue(coords);
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}
}

有人有什么想法吗?谢谢。

答案

我找到了解决方案!

如果你试图执行一个依赖于上下文/活动参数的线程,那么它可能无法工作。例如,如果使用getApplicationContext()函数,Toasts不能用于常见的Threads。

解决方案:使用处理程序或runOnUiThread()函数。他们将在主线程上执行命令行。看我的例子:

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable()
{
    @Override
    public void run() {
        //Here I can use getApplicationContext() because I'm on the UI Thread Context (I'm using a handler to do so).
        Toast.makeText(getApplicationContext(), "Starting listener...", Toast.LENGTH_SHORT).show();
        startListening();
    }
});

以上是关于位置监听器 - 不是从服务启动,而是从活动开始的主要内容,如果未能解决你的问题,请参考以下文章

应用程序总是从根活动重新开始,而不是恢复后台状态(已知错误)

活动归档不是从零开始的VueJS教学

不是从 Activity 启动 AlertDialog

是否可以修改网页的源并重新加载该页面而不是从服务器而是从编辑的源?

删除位置侦听器

检查 Windows 服务列表是不是正在运行,如果不是从批处理文件启动