Android - implementing startForeground for a service?

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

    This is my code to set the service to foreground:

    private void runAsForeground(){
        Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
        PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
                notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    
        Notification notification=new NotificationCompat.Builder(this)
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setContentText(getString(R.string.isRecording))
                                    .setContentIntent(pendingIntent).build();
    
        startForeground(NOTIFICATION_ID, notification);
    
    }
    

    I need to build a notification using PendingIntent, so that I can start my main activity from the notification.

    To remove the notification, just call the stopForeground(true);

    It is called in the onStartCommand(). Please refer to my code at : https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java

提交回复
热议问题