我正在尝试获取用户登录时的位置,并且该应用无法自动登录GPS
并崩溃。我猜我的LocationTrackerService.java
文件中有错误
当我的 compileSdkVersion 为26时,它运行正常。更新为28后,应用开始崩溃。
下面是我的 LocationTrackerService.java
public class LocationTrackerService extends Service {
static String agentId;
static String deviceModel;
static String deviceManufacture;
ConnectionDetector detector;
static String area ;
static String modArea;
Boolean isInternetPresent = false;
LocationCallback mCallback;
FusedLocationProviderClient client;
Context context;
LocationRequest locationRequest;
android.support.v4.app.NotificationCompat.Builder builder;
public LocationTrackerService() {
}
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
builder = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.app_name))
.setContentText("you are now logged in")
.setOngoing(true)
.setContentIntent(broadcastIntent)
.setSmallIcon(R.drawable.locator_icon);
startForeground(1, builder.build());
}
protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("receive", "received stop broadcast");
// Stop the service when the notification is tapped
// unregisterReceiver(stopReceiver);
}
};
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
// Toast.makeText(getApplicationContext(), "oncreated", Toast.LENGTH_SHORT).show();
SharedPreferences shared = getApplicationContext().getSharedPreferences("CTrack_vp", MODE_PRIVATE);
agentId = (shared.getString("agent_id", ""));
deviceModel = android.os.Build.MODEL;
deviceManufacture = android.os.Build.MANUFACTURER;
detector = new ConnectionDetector();
mCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Location location = locationResult.getLastLocation();
Double lat = location.getLatitude();
Double lang = location.getLongitude();
Double altitute = location.getAltitude();
Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(lat,lang,1);
area =addresses.get(0).getAddressLine(0);
modArea = area.replaceAll("[\" < > # % { } | \\ ^ ~ [ ] `]"," ");
Log.d("modarea", modArea);
// modArea = area.replaceAll("#"," ");
} catch (IOException e) {
e.printStackTrace();
}
isInternetPresent = detector.isOnline(getApplicationContext());
if(isInternetPresent){
new LocationTrackerService.SendLatLng().execute(lat,lang);
// Toast.makeText(LocationTrackerService.this, "location updated "+lat +" "+lang, Toast.LENGTH_SHORT).show();
}
}
};
/**
* interval 600000 (10 minutes)
* fast intervel 400000 (appxom 6 minutes)
*/
locationRequest = new LocationRequest();
locationRequest.setInterval(600000);
locationRequest.setFastestInterval(400000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
client = LocationServices.getFusedLocationProviderClient(this);
}
@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Toast.makeText(getApplicationContext(), "started", Toast.LENGTH_SHORT).show();
Log.d("services", "onStartCommand: started ");
client.requestLocationUpdates(locationRequest,mCallback , null);
buildNotification();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
client.removeLocationUpdates(mCallback);
// Toast.makeText(this, "location removed", Toast.LENGTH_SHORT).show();
Log.d("services", "onDestroy: stopped ");
unregisterReceiver(stopReceiver);
}
private static class SendLatLng extends AsyncTask<Double,Void,String> {
double lat, lng;
String jsonResponse;
@Override
protected String doInBackground(Double... params) {
try {
RequestHandler requestHandler = new RequestHandler();
if (String.valueOf(params[0]).length()>10){
lat= Double.parseDouble(String.valueOf(params[0]).substring(0,10));
System.out.println("insidelat--->"+lat);
}
else {
lat = params[0];
System.out.println("outsidelat--->"+lat);
}
if (String.valueOf(params[1]).length()>10){
lng=Double.parseDouble(String.valueOf(params[1]).substring(0,10));
System.out.println("insidelng--->"+lng);
}
else {
lng = params[1];
System.out.println("outsidelng--->"+lng);
}
jsonResponse = requestHandler.sendGetRequest(URL.LOCATION + "userId=" + agentId + "&latitude=" + lat + "&longitude=" + lng + "&deviceid=" + URLEncoder.encode(deviceManufacture) + "(" + URLEncoder.encode(deviceModel) + ")"+ "&address=" + modArea);
Log.d("url--->",URL.LOCATION + "userId=" + agentId + "&address=" + area+ "&latitude=" + lat + "&longitude=" + lng + "&deviceid=" + URLEncoder.encode(deviceManufacture) + "(" + URLEncoder.encode(deviceModel) + ")");
} catch (Exception e) {
Crashlytics.logException(e);
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
if (jsonResponse != null) {
JSONObject object = new JSONObject(jsonResponse);
JSONArray array = object.getJSONArray("Location");
JSONObject jsonObject = array.getJSONObject(0);
String str = jsonObject.getString("value");
Log.d("Location--", "Successfully send to DB" + str);
} else {
Log.d("Response--->", "Can't able to get response");
}
}
catch (JSONException e) {
Crashlytics.logException(e);
e.printStackTrace();
}
}
}
}
错误在下面
java.lang.RuntimeException: Unable to stop service com.LocationTrackerService@c1a04bf: java.lang.IllegalArgumentException: Receiver not registered: com.LocationTrackerService$1@f40678c
at android.app.ActivityThread.handleStopService(ActivityThread.java:3794)
at android.app.ActivityThread.-wrap26(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1902)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:187)
at android.app.ActivityThread.main(ActivityThread.java:7025)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:514)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.transasia.ctrackvp.LocationTrackerService$1@f40678c
at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:1257)
at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1491)
at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:656)
at com.transasia.ctrackvp.LocationTrackerService.onDestroy(LocationTrackerService.java:160)
at android.app.ActivityThread.handleStopService(ActivityThread.java:3776)
at android.app.ActivityThread.-wrap26(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1902)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:187)
at android.app.ActivityThread.main(ActivityThread.java:7025)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:514)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)