前台服务不工作后台

问题描述

我正在开发简单的后台位置应用程序。当应用程序打开时它运行良好,但当它的后台在五秒钟后停止工作但通知仍然在操作栏上,我可以在“工作服务”上看到服务。我很感激所有的帮助,因为我真的不知道我要做什么。这是我的代码

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(),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;
}

解决方法

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

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...