首页 > 解决方案 > NullPointerException:尝试从空对象引用上的字段“int com.google.android.gms.location.LocationRequest.a”读取

问题描述

我不明白为什么单击 startService 是一个前台服务时会出现此错误,并通知将应用程序更新位置保持在后台

atcom.raismedia.taxiclient.TrackingService.requestLocationUpdates(TrackingService.java:367) at com.raismedia.taxiclient.TrackingService.onConnected(TrackingService.java:349)

在这些行中

public void startLocationUpdates() {


        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;
        }
      -------------->367  LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);

    }
 
@Override
    public void onConnected(@Nullable Bundle bundle) {

        // Permissions ok, we get last location
        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;
        }
        currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
      ------->349  startLocationUpdates();
    }

这是我的服务

public class TrackingService extends Service implements TaskLoadedCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static Location currentLocation;


    public static Context context;

    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;


    public static final String PREFS_NAME = "LoginPrefs";

    private static final String TAG = TrackingService.class.getSimpleName();
    private TrackingService client;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        LocalBroadcastManager.getInstance(this).registerReceiver(
                mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
        if (googleApiClient == null) {

            googleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
//                .addApi(Places.GEO_DATA_API)
                    .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
//                .addApi(Places.PLACE_DETECTION_API)
//                .enableAutoManage(getActivity(), this)
                    .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
                    .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
                    .build();
            googleApiClient.connect();

        }


        buildNotification();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        String srv = intent.getStringExtra("switch");

        Log.i(TAG, "Received Stop Foreground Intent");
//        if (srv.equals("on")) {
//            Log.i(TAG, "Received Stop Foreground Intent");
//            //your end servce code
//            stopForeground(true);
//            stopSelf();
//        }


        return START_STICKY;
    }

//Create the persistent notification//

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void buildNotification() {
        String stop = "stop";
        //registerReceiver(stopReceiver, new IntentFilter(stop));
        PendingIntent broadcastIntent = PendingIntent.getBroadcast(
                this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);
        // Create the persistent notification
        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("App running and get your location")
                .setOngoing(true)
                .setContentIntent(broadcastIntent)
                .setSmallIcon(R.drawable.ic_calendar);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(14454, getNotification());

        //  startForeground(1, builder.build());
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startMyOwnForeground() {


        String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);
        String title = "Sticker Driver get your location";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.ic_delete)
                .setContentTitle(title)
                .setPriority(NotificationManager.IMPORTANCE_HIGH)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }

    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.O)
    private Notification getNotification() {

        String idChannel = "my_channel_01";
        Intent mainIntent;

        mainIntent = new Intent(getApplicationContext(), LauncherActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mainIntent, 0);

        NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationChannel mChannel = null;
        // The id of the channel.

        int importance = NotificationManager.IMPORTANCE_HIGH;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), null);
        builder.setContentTitle(getResources().getString(R.string.app_name))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setContentText("App is running in background");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(idChannel, getApplicationContext().getString(R.string.app_name), importance);
            // Configure the notification channel.
            mChannel.setDescription("App is running in background");
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);
        } else {
            builder.setContentTitle("Sticker Driver")
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
                    .setVibrate(new long[]{100, 250})
                    .setLights(Color.YELLOW, 500, 5000)
                    .setAutoCancel(true);
        }
        return builder.build();
    }


    protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            LocalBroadcastManager.getInstance(TrackingService.this).unregisterReceiver(mMessageReceiver);

            stopForeground(true);


            stopSelf();
        }
    };


    private void requestLocationUpdates() {


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            int permission = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION);

        }
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);

    }

    @Override
    public void onDestroy() {
        LocalBroadcastManager.getInstance(this).registerReceiver(
                stopReceiver, new IntentFilter("GPSLocationUpdates"));

        super.onDestroy();
        stopForeground(true);

        Toast.makeText(getApplicationContext(), " distroy", Toast.LENGTH_SHORT).show();


        stopSelf();

    }


    public void stopTracking() {

        Toast.makeText(getApplicationContext(), "stop tracking call", Toast.LENGTH_SHORT).show();
//         stopForeground(true);
        this.onDestroy();
        LocalBroadcastManager.getInstance(this).registerReceiver(
                stopReceiver, new IntentFilter("GPSLocationUpdates"));

    }

    private void sendMessageToActivity(Location l, String msg) {
        Intent intent = new Intent("GPSLocationUpdates");
        // You can also include some extra data.
        intent.putExtra("Status", msg);
        Bundle b = new Bundle();
        b.putParcelable("Location", l);
        intent.putExtra("Location", b);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }


    public final BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String message = intent.getStringExtra("Status");
            Bundle b = intent.getBundleExtra("Location");
            Location lastKnownLoc = (Location) b.getParcelable("Location");
            Toast.makeText(getApplicationContext(), "service class", Toast.LENGTH_SHORT).show();
            if (lastKnownLoc != null) {

                Log.i("Location : ", lastKnownLoc.getLatitude() + " latitute " + lastKnownLoc.getLongitude() + " Longitute " + lastKnownLoc.getTime());


                //  location location1 = new location(lastKnownLoc.getLatitude(), lastKnownLoc.getLongitude());

                /*
                 /// work for send letitude and longitude in server
                SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
                String access_token = "Bearer " + prefs.getString("access_token", null);
                int driver_id = prefs.getInt("Id", 0);
                BaseApiService mApiService;
                mApiService = UtilsApi.getAPIService();
                ping ping = new ping(driver_id, location1);
                mApiService.update(access_token, ping).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.isSuccessful()) {
                            Log.d("LocationUpdateService", "=============> successful");
                        } else {
                            Toast.makeText(getApplicationContext(), " failure " + response.message(), Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.d("debug", "onFailure: ERROR > " + t.toString());
                    }
                });
                // work for send latitude and longitude in server
                */

                Toast.makeText(getApplicationContext(), "latitute : " + lastKnownLoc.getLatitude() + " longitute :" + lastKnownLoc.getLongitude(), Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getApplicationContext(), lastKnownLoc.getLatitude() + " latitute " + lastKnownLoc.getLongitude() + " Longitute " + lastKnownLoc.getTime(), Toast.LENGTH_SHORT).show();

            }

        }
    };

    @Override
    public void onLocationChanged(Location location) {
        this.currentLocation = location;
//        Toast.makeText(context, "Ok", Toast.LENGTH_SHORT).show();

        if (currentLocation != null) {
            if (!M.getUserCategorie(context).equals("user_app"))
                new MainActivity.setCurrentLocation().execute(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
        }
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {

        // Permissions ok, we get last location
        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;
        }
        currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        startLocationUpdates();
    }


    public void startLocationUpdates() {


        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;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);

    }


    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }


    @Override
    public void onTaskDone(Object... values) {
        if(M.getUserCategorie(context).equals("user_app")) {
            if (M.getCurrentFragment(context).equals("home")) {
                if (FragmentHome.currentPolyline != null)
                    FragmentHome.currentPolyline.remove();
                FragmentHome.currentPolyline = FragmentHome.mMap.addPolyline((PolylineOptions) values[0]);
                FragmentHome.currentPolyline.setColor(Color.DKGRAY);

                LatLngBounds.Builder builder = new LatLngBounds.Builder();
                LatLng latLng1 = new LatLng(FragmentHome.departLocationReservation.getLatitude(), FragmentHome.departLocationReservation.getLongitude());
                LatLng latLng2 = new LatLng(FragmentHome.destinationLocationReservation.getLatitude(), FragmentHome.destinationLocationReservation.getLongitude());
                builder.include(latLng1);
                builder.include(latLng2);
                FragmentHome.mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 17));
            }/* else if (M.getCurrentFragment(context).equals("mes_requetes_accueil")){
                if (FragmentHome.currentPolyline != null)
                    FragmentHome.currentPolyline.remove();
                FragmentHome.currentPolyline = FragmentHome.mMap.addPolyline((PolylineOptions) values[0]);
                FragmentHome.currentPolyline.setVehicleColor(Color.DKGRAY);

                LatLngBounds.Builder builder = new LatLngBounds.Builder();
                LatLng latLng1 = new LatLng(FragmentHome.departLocationMesRequetes.getLatitude(), FragmentHome.departLocationMesRequetes.getLongitude());
                LatLng latLng2 = new LatLng(FragmentHome.destinationLocationMesRequetes.getLatitude(), FragmentHome.destinationLocationMesRequetes.getLongitude());
                builder.include(latLng1);
                builder.include(latLng2);
                FragmentHome.mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 17));
            } else if (M.getCurrentFragment(context).equals("historic")){
                if (BottomSheetFragmentHistoric.currentPolyline != null)
                    BottomSheetFragmentHistoric.currentPolyline.remove();
                BottomSheetFragmentHistoric.currentPolyline = BottomSheetFragmentHistoric.mMap.addPolyline((PolylineOptions) values[0]);
                BottomSheetFragmentHistoric.currentPolyline.setVehicleColor(Color.DKGRAY);

                LatLngBounds.Builder builder2 = new LatLngBounds.Builder();
                LatLng latLng3 = new LatLng(BottomSheetFragmentHistoric.clientLocation.getLatitude(),BottomSheetFragmentHistoric.clientLocation.getLongitude());
                LatLng latLng4 = new LatLng(BottomSheetFragmentHistoric.destinationLocation.getLatitude(),BottomSheetFragmentHistoric.destinationLocation.getLongitude());
                builder2.include(latLng3);
                builder2.include(latLng4);
//            BottomSheetFragmentRide.mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder2.build(), 100));
            }else{
                if (BottomSheetFragmentMyRide.currentPolyline != null)
                    BottomSheetFragmentMyRide.currentPolyline.remove();
                BottomSheetFragmentMyRide.currentPolyline = BottomSheetFragmentMyRide.mMap.addPolyline((PolylineOptions) values[0]);
                BottomSheetFragmentMyRide.currentPolyline.setVehicleColor(Color.DKGRAY);

                LatLngBounds.Builder builder2 = new LatLngBounds.Builder();
                LatLng latLng3 = new LatLng(BottomSheetFragmentMyRide.clientLocation.getLatitude(),BottomSheetFragmentMyRide.clientLocation.getLongitude());
                LatLng latLng4 = new LatLng(BottomSheetFragmentMyRide.destinationLocation.getLatitude(),BottomSheetFragmentMyRide.destinationLocation.getLongitude());
                builder2.include(latLng3);
                builder2.include(latLng4);
                BottomSheetFragmentMyRide.mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder2.build(), 100));
            }*/
        }else{
            /*if(M.getCurrentFragment(context).equals("requete")){
                if (BottomSheetFragmentRide.currentPolyline != null)
                    BottomSheetFragmentRide.currentPolyline.remove();
                BottomSheetFragmentRide.currentPolyline = BottomSheetFragmentRide.mMap.addPolyline((PolylineOptions) values[0]);
                BottomSheetFragmentRide.currentPolyline.setVehicleColor(Color.DKGRAY);

                LatLngBounds.Builder builder2 = new LatLngBounds.Builder();
                LatLng latLng3 = new LatLng(BottomSheetFragmentRide.clientLocation.getLatitude(),BottomSheetFragmentRide.clientLocation.getLongitude());
                LatLng latLng4 = new LatLng(BottomSheetFragmentRide.destinationLocation.getLatitude(),BottomSheetFragmentRide.destinationLocation.getLongitude());
                builder2.include(latLng3);
                builder2.include(latLng4);
//                BottomSheetFragmentRide.mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder2.build(), 17));
            }else{
                if (BottomSheetFragmentCourse.currentPolyline != null)
                    BottomSheetFragmentCourse.currentPolyline.remove();
                BottomSheetFragmentCourse.currentPolyline = BottomSheetFragmentCourse.mMap.addPolyline((PolylineOptions) values[0]);
                BottomSheetFragmentCourse.currentPolyline.setVehicleColor(Color.DKGRAY);

                LatLngBounds.Builder builder2 = new LatLngBounds.Builder();
                LatLng latLng3 = new LatLng(BottomSheetFragmentCourse.clientLocation.getLatitude(),BottomSheetFragmentCourse.clientLocation.getLongitude());
                LatLng latLng4 = new LatLng(BottomSheetFragmentCourse.destinationLocation.getLatitude(),BottomSheetFragmentCourse.destinationLocation.getLongitude());
                builder2.include(latLng3);
                builder2.include(latLng4);
//                BottomSheetFragmentCourse.mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder2.build(), 17));
            }*/
        }
    }
}

我必须做什么?

标签: javaandroidnullpointerexceptiongoogle-api-clientbackground-foreground

解决方案


推荐阅读