Android - implementing startForeground for a service?

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

    From your main activity, start the service with the following code:

    Intent i = new Intent(context, MyService.class); 
    context.startService(i);
    

    Then in your service for onCreate() you would build your notification and set it as foreground like so:

    Intent notificationIntent = new Intent(this, MainActivity.class);
    
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                    notificationIntent, 0);
    
    Notification notification = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.app_icon)
                    .setContentTitle("My Awesome App")
                    .setContentText("Doing some work...")
                    .setContentIntent(pendingIntent).build();
    
    startForeground(1337, notification);
    

提交回复
热议问题