Java 前台服务在Android 9中不起作用(API 28)

Java 前台服务在Android 9中不起作用(API 28),java,android,Java,Android,我想有一个前台服务,我写的代码。 但问题是,该应用程序在API 26及以下版本上运行良好,但在API 28中运行不好。 API 28中的问题是,它作为后台服务工作,如果关闭应用程序,服务也会关闭。 这是我的密码: 我的服务: import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.Pendi

我想有一个前台服务,我写的代码。 但问题是,该应用程序在API 26及以下版本上运行良好,但在API 28中运行不好。 API 28中的问题是,它作为后台服务工作,如果关闭应用程序,服务也会关闭。 这是我的密码: 我的服务:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.widget.Toast;

public class MyService extends Service {

    private Context context = null;
    private static final int NOTIFICATION_ID = 1;
    private static final String CHANNEL_ID = "ChargeScreenService";

    private Looper serviceLooper;
    private ServiceHandler serviceHandler;
    private BatteryBroadCast batteryBroadCast;
    private NotificationManager notificationManager;
    private Notification notification;

    // Handler that receives messages from the thread
    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            // Normally we would do some work here, like download a file.
            // For our sample, we just sleep for 5 seconds.
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    batteryBroadCast = new BatteryBroadCast(MyService.this);
                    batteryBroadCast.chargingChanges();
                }
            });
            thread.start();
            // Stop the service using the startId, so that we don't stop
            // the service in the middle of handling another job
            //stopSelf(msg.arg1);
        }
    }

    @Override
    public void onCreate() {
        // Start up the thread running the service. Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block. We also make it
        // background priority so CPU-intensive work doesn't disrupt our UI.
        HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);

        thread.start();

        // Get the HandlerThread's Looper and use it for our Handler
        serviceLooper = thread.getLooper();
        serviceHandler = new ServiceHandler(serviceLooper);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

        createNotificationChannel();

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = new Notification.Builder(this, CHANNEL_ID)
                    .setContentTitle("Hi")
                    .setContentText("Hello")
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setContentIntent(pendingIntent)
                    .setTicker("HI")
                    .setOngoing(true)
                    .build();

            notificationManager.notify(NOTIFICATION_ID, notification);
        } else {
            notification = new Notification.Builder(this)
                    .setContentTitle("Hi")
                    .setContentText("Hello")
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setContentIntent(pendingIntent)
                    .setTicker("HI")
                    .setOngoing(true)
                    .build();
        }

        startForeground(1, notification);

        Message msg = serviceHandler.obtainMessage();
        msg.arg1 = startId;
        serviceHandler.sendMessage(msg);

        // If we get killed, after returning from here, restart
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // We don't provide binding, so return null
        return null;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "ChargeScreenService";
            String description = "Service";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}
主要活动:

...
startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(intent);
                } else {
                    startService(intent);
                }

            }
        });
...
最后,我在AndroidManifest文件中添加了权限。
也定义了我的服务

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

测试设备: 三星galaxy J7 pro(型号:SM-J730F)(真实设备)
虚拟设备:Genymotion Android 6

如果您的应用程序的API级别为26或更高,则当应用程序本身不在前台时,系统会对运行后台服务施加限制。在大多数情况下,您的应用程序都应该使用预定作业。

您使用的是哪部手机testing@amin三星galaxy J7 pro(型号:SM-J730F)你看到任何崩溃日志了吗?@amin No只是工作不好。