Android - implementing startForeground for a service?

前端 未结 11 1145
不思量自难忘°
不思量自难忘° 2020-11-22 06:26

So I\'m not sure where/how to implement this method to make my service run in the foreground. Currently I start my service by the following in another activity:

<         


        
11条回答
  •  一向
    一向 (楼主)
    2020-11-22 07:10

    Solution for Oreo 8.1

    I've encountered some problems such as RemoteServiceException because of invalid channel id with most recent versions of Android. This is how i solved it:

    Activity:

    override fun onCreate(savedInstanceState: Bundle?) {
        val intent = Intent(this, BackgroundService::class.java)
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }
    

    BackgroundService:

    override fun onCreate() {
        super.onCreate()
        startForeground()
    }
    
    private fun startForeground() {
    
        val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channelId =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    createNotificationChannel()
                } else {
                    // If earlier version channel ID is not used
                    // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                    ""
                }
    
        val notificationBuilder = NotificationCompat.Builder(this, channelId )
        val notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build()
        startForeground(101, notification)
    }
    
    
    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(): String{
        val channelId = "my_service"
        val channelName = "My Background Service"
        val chan = NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_HIGH)
        chan.lightColor = Color.BLUE
        chan.importance = NotificationManager.IMPORTANCE_NONE
        chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
        val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        service.createNotificationChannel(chan)
        return channelId
    }
    

    JAVA EQUIVALENT

    public class YourService extends Service {
    
        // Constants
        private static final int ID_SERVICE = 101;
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
            return START_STICKY;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            // do stuff like register for BroadcastReceiver, etc.
    
            // Create the Foreground Service
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
            Notification notification = notificationBuilder.setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setPriority(PRIORITY_MIN)
                    .setCategory(NotificationCompat.CATEGORY_SERVICE)
                    .build();
    
            startForeground(ID_SERVICE, notification);
        }
    
        @RequiresApi(Build.VERSION_CODES.O)
        private String createNotificationChannel(NotificationManager notificationManager){
            String channelId = "my_service_channelid";
            String channelName = "My Foreground Service";
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
            // omitted the LED color
            channel.setImportance(NotificationManager.IMPORTANCE_NONE);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationManager.createNotificationChannel(channel);
            return channelId;
        }
    }
    

提交回复
热议问题