我是android服务的新手,我有一些疑问

问题描述

  1. 我想开发一种服务,即使该应用被杀死也可以在后台运行。在我的场景中,我正在使用融合位置提供者客户端获取位置更新,并将其发送到数据库。问题是,当我使用主页按钮位置将应用程序置于后台时,更新停止并且大约在1分钟内服务被杀死。如果我从最近的应用程序托盘中删除了该应用程序,服务将再次被终止。我已经读过,在后台服务中使用fusedlocationproviderclient有局限性。 “如果您的应用程序在后台运行,则位置系统服务每小时仅会几次为您的应用程序计算一个新位置。”与此有关吗?

清单中的服务

<service
        android:name=".Background_Location_Service"
        android:enabled="true"></service>
    

在这里启动服务:

Intent service_intent=new Intent(getApplicationContext(),Background_Location_Service.class);
    service_intent.putExtra("username",username);
    startService(service_intent);

我的服务:

public class Background_Location_Service extends Service {
private static Double lat;
private static Double lon;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback locationCallback;
private LocationRequest locationRequest;
private String username;
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
    username = intent.getExtras().getString("username");
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                lat = location.getLatitude();
                lon = location.getLongitude();
                
                //Sending latitude,longitude and username to database
                Call<ResponseBody> call = Retrofit_Client
                        .getInstance()
                        .getAPI()
                        .send_location(lat,lon,username);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
                        try {
                            String response_status = response.body().string();
                            Toast.makeText(Background_Location_Service.this,response_status,Toast.LENGTH_SHORT).show();
                        } catch (IOException e) {
                            e.printstacktrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call,Throwable t) {
                        Toast.makeText(Background_Location_Service.this,t.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    };
    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.
    }
    //requesting updates
    fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,Looper.getMainLooper());

    Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
    return Service.START_STICKY;
}

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

@Override
public void onDestroy() {
    fusedLocationProviderClient.removeLocationUpdates(locationCallback);
    super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {

    Intent restartService = new Intent(getApplicationContext(),this.getClass());
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),1,restartService,PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME,5000,pendingIntent);


}}
  1. 我了解到,必须开发前台服务,包括通知以连续运行服务。使用这种方法可以实现吗?还是有更好的方法

  2. 我阅读了可以使用workmanager的信息,因此它将使用Jobscheduler或Alarmmanager自动清除。它也能够应付打ze睡模式。那么我可以开发工作管理器来定期(例如每5分钟一次)获取一个已知位置,而不是请求位置更新吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)