Android development basic service Service

Try to understand the service among the four major components of Android development as simply as possible, using simple examples and language.

concept

It runs in the background for a long time and has no interaction with the user. For example, music can be played in the background while you can read books, browse news, etc.

Configuration 

Since Service is also one of the four major components, it also needs to be registered in the project's configuration file. Specifically, add statements such as: in the AndroidManifest.xml file:

<service android:name="cn.uprogrammer.sensordatacollect.IPSService"></service>

Run service

First, write two buttons on the app interface to set the service to start or stop.

    <Button
        android:onClick="startServiceClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启服务"/>

    <Button
        android:onClick="stopServiceClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停止服务"/>

Next, write the code to start and pause the service

    //开启服务
    public void startServiceClick(View view){
        Intent intent = new Intent();
        intent.setClass(this,IPSService.class);
        startService(intent);
    }

    //停止服务
    public void stopServiceClick(View view){
        Intent intent = new Intent();
        intent.setClass(this,IPSService.class);
        stopService(intent);
    }

 

Guess you like

Origin blog.csdn.net/danielxinhj/article/details/132559943