在FirebaseMessagingService中获取当前位置GPS

3

我不明白为什么在我的华为P8 lite手机上SEND_POSITION通知可以正常工作,但在三星Note3上会导致应用崩溃。我错在哪里了?

With SAMSUNG I get this error:
        E/UncaughtException: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:200)
        at android.os.Handler.<init>(Handler.java:114)
        at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:223)
        at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:223)
        at android.location.LocationManager.wrapListener(LocationManager.java:851)
        at android.location.LocationManager.requestLocationUpdates(LocationManager.java:864)
        at android.location.LocationManager.requestLocationUpdates(LocationManager.java:459)
        at com.mifra.mifraqronda.GPSTracker.getLocation(GPSTracker.java:37)
        at com.mifra.mifraqronda.FirebaseMessagingService.showNotification(FirebaseMessagingService.java:43)
        at com.mifra.mifraqronda.FirebaseMessagingService.onMessageReceived(FirebaseMessagingService.java:30)
        at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(Unknown Source)
        at com.google.firebase.iid.zzc.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

代码如下:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.RemoteMessage;

import java.io.IOException;

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

    Vibrator vib;
    DatabaseHelper database = new DatabaseHelper(this);

    String urlSite = "https://qronda.mifra.info/index.php";
    String parameterUpdatePositionUser = "";
    String apiKeyMifra = "fd57700b-af6c-4ba6-9ad9-cfc592028f35";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage){
        showNotification(remoteMessage.getData().get("message"));
    }

    private void showNotification(String message) {

        String[] messageSplit = message.split(":");

        if(messageSplit[0].equals("SEND_POSITION")){
            Log.wtf("Mifra in Notify", "Message: "+message);

            // controllo posizione GPS
            GPSTracker gps = new GPSTracker(this);
            boolean toast = false;
            Location location = gps.getLocation(toast);
            if (gps.getLocation(toast) == null) {
                vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                vib.vibrate(1000);
                //Toast.makeText(getApplicationContext(), "GPS non agganciato impossibile otterene la tua posizione", Toast.LENGTH_SHORT).show();
                Log.d("Mifra SendPosition", "GPS non agganciato impossibile otterene la tua posizione");
        } else {

            double lat = location.getLatitude();
            double lng = location.getLongitude();
            String stringLat = Double.toString(lat);
            String stringLng = Double.toString(lng);

            Login login = database.selectLogin(1);
            // task recupero dati sitoWeb login utente
            parameterUpdatePositionUser = "option=com_mifrageo&task=app.updatePositionUser&format=json&id_user=" + login.getIduser()
                    + "&lat=" + stringLat + "&lng=" + stringLng + "&apiKey=" + apiKeyMifra;
            new UpdatePositionUserTask().execute(urlSite);

        }
    }

    // Evento dopo la task updatePositionUsers
    private class UpdatePositionUserTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {

            try {
                return ConnectAppMySql.postDati(urls[0], parameterUpdatePositionUser);
            } catch (IOException e) {
                return "Impossibile ricevere i dati della pagina web, URL invalido";
            }
        }

        @Override
        protected void onPostExecute(String result) {

            try {

                Log.d("Mifra SendPosition", "Posizione inviata e salvata" + result);

                //Toast.makeText(getApplicationContext(), "Posizione inviata e salvata" + result, Toast.LENGTH_LONG).show();

            } catch (Throwable t) {
                Log.e("Mifra Monitor JSON", "Impossibile analizzare array JSON: \"" + result + "\"");
            }
        }
    }
}

我该如何解决这个问题?


有人能帮帮我吗? - Giuseppe Piccolo
我尝试了...但是在上下文级别遇到了问题...这是由于服务所需的无效上下文...同时也在寻求帮助... - Bhuro
1个回答

1
根据这个问题,你需要按照以下方式进行:

@Override
public void onMessageReceived(RemoteMessage remoteMessage){

    // some codes here
    new Handler(Looper.getMainLooper()).post(() -> {
    // your get location attempt codes
    });


}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接