前台服务不工作后台

如何解决前台服务不工作后台

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

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.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?