Android - implementing startForeground for a service?

前端 未结 11 1260
不思量自难忘°
不思量自难忘° 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:05

    If you want to make IntentService a Foreground Service

    then you should override onHandleIntent()like this

    Override
    protected void onHandleIntent(@Nullable Intent intent) {
    
    
        startForeground(FOREGROUND_ID,getNotification());     //<-- Makes Foreground
    
       // Do something
    
        stopForeground(true);                                // <-- Makes it again a normal Service                         
    
    }
    

    How to make notification ?

    simple. Here is the getNotification() Method

    public Notification getNotification()
    {
    
        Intent intent = new Intent(this, SecondActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
    
    
        NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);
        foregroundNotification.setOngoing(true);
    
        foregroundNotification.setContentTitle("MY Foreground Notification")
                .setContentText("This is the first foreground notification Peace")
                .setSmallIcon(android.R.drawable.ic_btn_speak_now)
                .setContentIntent(pendingIntent);
    
    
        return foregroundNotification.build();
    }
    

    Deeper Understanding

    What happens when a service becomes a foreground service

    This happens

    What is a foreground Service ?

    A foreground service,

    • makes sure that user is actively aware of that something is going on in the background by providing the notification.

    • (most importantly) is not killed by System when it runs low on memory

    A use case of foreground service

    Implementing song download functionality in a Music App

提交回复
热议问题