[JAVA] Try using the service on Android Oreo

At the beginning

On Android, if you want to process in the background, you will use service. Let's examine service and create a simple sample code.

Service format

There are two types of services, with different methods to call.

・ Started service Start with startService (). The started service will continue to move until it is stopped. It does not return the result to the caller, it just does the work.

· Bound service Bind with bindService (). You can control the bound service, such as sending requests and getting results. However, when the calling Activity ends, it ends at the same time.

Service callback method

onCreate() Since it is called once at the beginning, it will be initialized. onStartCommand() Write the process to be executed by the service. onDestroy() Service termination processing onBind() If you call it with bindService (), you can call it.

Services on Android Oreo

Background execution limit Restrictions have been added to background processing from Android Oreo (8.0 / API Level 26). Therefore, the newly introduced startForegroundService () replaces the above startService Is used. (Actually, it is necessary to separate the processing according to the SDK version)

There were various specifications when using startForegroundService (). Demonstrate background service restrictions from Android O. The use cases are summarized here in an easy-to-understand manner, so I used it as a reference.

Source

Press the start button to start the service, and the stop button to stop the service. Since the log is output 10 seconds after the service starts, try checking by putting the application in the background before that.

Added service class to Manifest

AndroidManifest.xml


<service android:name=".TestService"/>

MainActivity (button settings only)

MainActivity.java


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startButton = findViewById(R.id.button_start);
        Button stopButton = findViewById(R.id.button_stop);

        //Start of the service
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent serviceIntent = new Intent(getApplication(), TestService.class);
                startForegroundService(serviceIntent);
            }
        });

        //Service outage
        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent serviceIntent = new Intent(getApplication(), TestService.class);
                stopService(serviceIntent);
            }
        });
    }
}

Service class

TestService.java


public class TestService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("DEBUG", "called TestService.onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("DEBUG", "called TestService.onStartCommand()");
        String channelId = "service";
        String title = "TestService";

        //Notification settings
        NotificationManager notificationManager =
                (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel =
                new NotificationChannel(channelId, title, NotificationManager.IMPORTANCE_DEFAULT);

        if(notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(getApplicationContext(), channelId)
                    .setContentTitle(title)
                    .setSmallIcon(R.drawable.menu)
                    .setContentText("service start")
                    .build();

            //Run in the foreground
            startForeground(1, notification);

            //Log output after 10 seconds
            try {
                Thread.sleep(10000);
                Log.i("INFO", "processing service");
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
        }

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("DEBUG", "called TestService.onDestroy()");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Where I was addicted

An event occurred in which crashes occurred repeatedly when the service was started. When I looked it up, it was due to the setting of the notification passed to the argument with startForeground (). In Android 8.0, it seems that you should not specify Adaptive icon with Notification.setSmallIcon (). I crashed with R.mipmap.ic_launcher. It is modified to specify an appropriate image for avoidance. System UI crashes when displaying notifications on Android 8.0

Summary

I tried to verify the movement of the service easily. (The verification method wasn't very clean, but ...) The implementation method differs depending on the version, and there are various restrictions, so it seems that more study is required to make good use of it.

The following is a reference site. How to use [Android] Service Android Oreo: Foreground notifications and services (https://rakuishi.com/archives/android-oreo-notification-foreground/) Services | Android Developers

Recommended Posts

Try using the service on Android Oreo
Try using the Emotion API from Android
Try communication using gRPC on Android + Java server
Run the Android emulator on Docker using Android Emulator Container Scripts
Try image classification using TensorFlow Lite on Android (JAVA)
Try using the query attribute of Ruby on Rails
Try launching a webAP server on the micro using Helidon
Try using Redmine on Mac docker
[Android] Get the date on Monday
Save ArrayList using GSON on Android
Try using the messaging system Pulsar
Try using the two-point measurement function of Firebase Performance Monitoring. [Android]
Try using || instead of the ternary operator
Try using the Stream API in Java
Try using the Rails API (zip code)
Sobel filter using OpenCV on Android (Java)
Try calling the CORBA service in Java 11+
Try Health Check on Azure App Service.
Try the Docker environment on AWS ECS
Try using the Wii remote with Java
[Android] How to turn the Notification panel on and off using StatusBarManager
Try using libGDX
Using templates on the classpath with Apache Velocity
[Android] Get the tapped position (coordinates) on the screen
Try using Maven
Try using powermock-mockito2-2.0.2
Try using GraalVM
[Android] List all setting items on the setting screen
Android application development using Unity + ARCore on Ubuntu
Try using jmockit 1.48
Try using sql-migrate
Try Azure Service Fabric (Java) on Mac-Local Environment
Beginners try using android studio Part 2 (event processing)
Try calling the CORBA service from Spring (Java)
Try local file search using Fess on CentOS7
Try local file search using Fess on CentOS8
Tips for using the Spotify app on Ubuntu
Beginners try using android studio Part 1 (Hello World)
(Android) Try to display static text using DataBinding
Try accessing the dataset from Java using JZOS
Try using SwiftLint
Try using Log4j 2.0
Translator using Microsoft Translator Text API on Android ~ Implementation ~
Try using the COTOHA API parsing in Java
Using Java 8 with Bluemix (on Liberty Runtime & DevOps Service)
[Android] Solution when the camera cannot be started on Android 9
Try implementing the Eratosthenes sieve using the Java standard library
Deploy Java apps on the IBM Cloud Kubernetes service
[Android] Display images and characters on the ViewPager tab
[Introduction] Display Android Studio Hello World on the emulator
Try global hooking in Java using the JNativeHook library
Limit the number of threads using Java's Executor Service
Command to try using Docker for the time being
I want to simplify the log output on Android
Until the Google Assistant sample runs on Android Things
Try using Axon Framework
Try using JobScheduler's REST-API
Try DisplayLink on Ubuntu 20.04
Try using java.lang.Math methods
Try using PowerMock's WhiteBox
Try OpenLiteSpeed on CentOS8