如何解决NullPointerException:尝试从null对象引用上的字段'int com.google.android.gms.location.LocationRequest.a'中读取
我无法理解为什么单击startService时出现此错误 是具有通知的前台服务,用于将应用程序更新位置保持在后台
atcom.raismedia.taxiclient.TrackingService.requestLocationUpdates(TrackingService.java:367) 位于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,// 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,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(),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});
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,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_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
int permission = ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleapiclient,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,// 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,// 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,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));
}*/
}
}
}
我该怎么办?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。