Create foreground services and apply for permissions

What is front desk service?

Foreground services are those that are considered user-aware (user-approved) and are not allowed to be killed by the system when the system runs out of memory . A foreground service must provide a notification to the status bar, which is placed under the Ongoing heading - which means that the notification can only be dismissed when the service is terminated or the notification is actively removed from the foreground .

 

Steps to create a foreground service:

1. Create a class and extend Service, in the onCreate() method, build a notification and call the startForeground() method

public void onCreate() {
    super.onCreate();
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("This is content title")
            .setContentText("This is content text")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .setContentIntent(pi)
            .build();
    startForeground(1, notification);
}

 

2. Start the Service in the main thread

 

  

Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // start the service

 

 

3. Apply for runtime permissions

if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE }, 1);
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326191287&siteId=291194637