我正在开发简单的后台位置应用程序。当应用程序打开时它运行良好,但当它的后台在五秒钟后停止工作但通知仍然在操作栏上,我可以在“工作服务”上看到服务。我很感激所有的帮助,因为我真的不知道我要做什么。这是我的代码。
MainActivity.java
private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_LOCATION_PERMISSION);
} else {
startLocationService();
}
}
});
findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopLocationService();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_LOCATION_PERMISSION && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationService();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private boolean isLocationServiceRunning() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (activityManager != null) {//TODO:
for (ActivityManager.RunningServiceInfo service :
activityManager.getRunningServices(Integer.MAX_VALUE)) {
if (LocationService.class.getName().equals(service.service.getClassName())) {
if (service.foreground) {
return true;
}
}
}
return false;
}
return false;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startLocationService() {
if (!isLocationServiceRunning()) {
Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.setAction(Constans.ACTION_START_LOCATION_SERVICE);
startService(intent);
Toast.makeText(this, "Location service started", Toast.LENGTH_LONG).show();
}
}
private void stopLocationService() {
if (isLocationServiceRunning()) {
Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.setAction(Constans.ACTION_STOP_LOCATION_SERVICE);
startService(intent);
Toast.makeText(this, "Location service stopped", Toast.LENGTH_LONG).show();
}
}
我的服务类.java
private LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult != null && locationResult.getLastLocation() != null) {
double latitude = locationResult.getLastLocation().getLatitude();
double longitude = locationResult.getLastLocation().getLongitude();
System.out.println("location: " + latitude + "," + longitude);
}
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("not yet implemented");
}
private void startLocationService() {
String channelId = "location_notification_channel";
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelId);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Location Service");
builder.setDefaults(NotificationCompat.DEFAULT_ALL);
builder.setContentText("Running");
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(false);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (notificationManager != null
&& notificationManager.getNotificationChannel(channelId) == null) {
NotificationChannel notificationChannel = new NotificationChannel(
channelId,
"Location Service",
NotificationManager.IMPORTANCE_HIGH
);
notificationChannel.setDescription("This channel is used by location service");
notificationManager.createNotificationChannel(notificationChannel);
}
}
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(4000);
locationRequest.setFastestInterval(2000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
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.getFusedLocationProviderClient(this)
.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
startForeground(Constans.LOCATION_SERVICE_ID, builder.build());
}
private void stopLocationService() {
LocationServices.getFusedLocationProviderClient(this)
.removeLocationUpdates(locationCallback);
stopForeground(true);
stopSelf();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
if (action != null) {
if (action.equals(Constans.ACTION_START_LOCATION_SERVICE)) {
startLocationService();
} else if (action.equals(Constans.ACTION_STOP_LOCATION_SERVICE)) {
stopLocationService();
}
}
}
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}