首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尝试调用虚拟方法的com.google.android.gms.location.FusedLocationProviderClient.getLastLocation()‘com.google.android.gms.tasks.Task

尝试调用虚拟方法的com.google.android.gms.location.FusedLocationProviderClient.getLastLocation()‘com.google.android.gms.tasks.Task
EN

Stack Overflow用户
提问于 2022-09-15 14:28:24
回答 1查看 201关注 0票数 0

2022-09-15 16:22:07.477 29909 -29997/io.sendNow. reference /AndroidRuntime:致命异常:Firebase-消息传递-意图-处理进程: io.sendnow.sendnow,PID: 29909 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法的com.google.android.gms.tasks.Task java.lang.NullPointerException

我试图获得最近的位置,并把它发送到我的服务器,不幸的是,应用程序崩溃的错误,如上文所示。

MyFirebaseMessagingService类:

代码语言:javascript
运行
复制
package io.ionic.starter;

import android.Manifest;
import android.accessibilityservice.AccessibilityService;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import io.sendnow.sendnow.MainActivity;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

public class MyFirebaseMessagingService extends FirebaseMessagingService {


  private SharedPreferences sharedPref;
  private SharedPreferences.Editor editor;

  private static final String TAG = "MyFirebaseMsgService";

  private FusedLocationProviderClient fusedLocationClient;

  protected void onCreate(Bundle savedInstanceState) {
    // ...

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(MyFirebaseMessagingService.this);
  }

(.)

代码语言:javascript
运行
复制
  private void handleNow() {
    Log.d(TAG, "Short lived task is done.");

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
      // TODO: Consider calling
      //    ActivityCompat#requestPermissions
      // here to request the missing permissions, and then overriding
      //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
      //                                          int[] grantResults)
      // to handle the case where the user grants the permission. See the documentation
      // for ActivityCompat#requestPermissions for more details.
      return;
    }

    fusedLocationClient.getLastLocation()
      .addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
          // Got last known location. In some rare situations this can be null.
          if (location != null) {
            // Logic to handle location object

            boolean isCharging = MyFirebaseMessagingService.getCharging(getApplicationContext());
            float batteryLevel = MyFirebaseMessagingService.getBatteryLevel(getApplicationContext());

            String username = sharedPref.getString("sendnow_username", "nativestorage_null");
            String userId = sharedPref.getString("sendnow_user_id", "nativestorage_null");
            String licenseholderId = sharedPref.getString("sendnow_licenseholder_id", "nativestorage_null");

            String urlString = "URL"; // URL to call
            String params = "username=" + username + "&" + "user_id=" + userId + "&" + "licenseholder_id=" + licenseholderId +
              "&" + "altitude=" + location.getAltitude() + "&" + "speed=" + location.getSpeed() + "&" + "location=" +
              location.getLatitude() + "," + location.getLongitude() + "&" + "lastGpsUpdate=" + location.getTime() + "&" +
              "charging=" + isCharging + "&" + "batteryLevel=" + batteryLevel;
            OutputStream out = null;

            try {
              URL url = new URL(urlString);
              HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
              out = new BufferedOutputStream(urlConnection.getOutputStream());
              urlConnection.setRequestMethod("POST");

              BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
              writer.write(params);
              writer.flush();
              writer.close();
              out.close();

              urlConnection.connect();
            } catch (Exception e) {
              System.out.println(e.getMessage());
            }
          }
        }
      });
  }

 
}

build.gradle(:app)

代码语言:javascript
运行
复制
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    defaultConfig {
        applicationId "io.sendnow.sendnow"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 131
        versionName "1.20.4"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    flatDir{
        dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
    }
}

configurations.all {
  resolutionStrategy {
    force "com.google.android.gms:play-services-ads:21.1.0"
    force "com.google.android.gms:play-services-basement:18.1.0"
    force "com.google.android.gms:play-services-gcm:17.0.0"
    force "com.google.android.gms:play-services-analytics:18.0.1"

    force "com.google.android.gms:play-services-location:20.0.0"
    force "com.google.android.gms:play-services-tagmanager:18.0.1"
  }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
    implementation project(':capacitor-android')
  implementation 'com.google.android.gms:play-services-location:20.0.0'
  testImplementation "junit:junit:$junitVersion"
    androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
    androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"

  // Import the Firebase BoM
  implementation platform('com.google.firebase:firebase-bom:30.3.2') {
    force = true;
  }

  implementation 'com.google.firebase:firebase-analytics'
  implementation "androidx.work:work-runtime:2.7.1"
  implementation "com.google.firebase:firebase-messaging:23.0.8"


  // Add the dependencies for any other desired Firebase products
  // https://firebase.google.com/docs/android/setup#available-libraries
    implementation project(':capacitor-cordova-android-plugins')
}


apply from: 'capacitor.build.gradle'
EN

回答 1

Stack Overflow用户

发布于 2022-09-16 10:52:43

这是行不通的:

代码语言:javascript
运行
复制
 protected void onCreate(Bundle savedInstanceState) {
    // ...

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(MyFirebaseMessagingService.this);
  }

我把它移到handleNow函数中,这样fusedLocationClient就真的存在了。我是一个Java/Android开发人员,所以也许这对其他开发人员来说很有意义,但我希望我能帮助别人回答这个问题。

代码语言:javascript
运行
复制
private void handleNow() {
    Log.d(TAG, "Short lived task is done.");

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(MyFirebaseMessagingService.this);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73732953

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档