android Initial Services

Keywords: Android

Today, let's talk about one of Android's four basic components: services·




Let's start with a simple typesetting

-<LinearLayout tools:context="com" android:orientation="vertical" android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">

<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="start" android:text="Startup service"/>

<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="stop" android:text="Out of Service"/>

</LinearLayout>

Two buttons to simulate service opening and closing


Corresponding MainActivity

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intent = new Intent(this,MyServices1.class);
    }

    public void start(View view){
            //Opening service
        startService(intent);

    }

    public void stop(View view){
        stopService(intent);//Shut down service
    }

}


Then you need to create a new class to inherit Service and restore its methods

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * @author Zking-Snail
 * @time 2017/2/10 19:09
 * @Version ${REV}
 */
public class MyServices extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("test","onBind");
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("test","onCreate");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String data=intent.getStringExtra("data");

        Log.i("test","onStartCommand,"+data);

        new MyThread(startId).start();

        return super.onStartCommand(intent, flags, startId);
    }

    class MyThread extends Thread{
        private int startId;

        public MyThread(int startId) {
            this.startId = startId;
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i <10 ; i++) {
                Log.i("test","i="+i);
                SystemClock.sleep(1000);
            }

Then I'm going to simulate the operation of printing.


You can see that I've opened another thread here to print this time-consuming operation.


Personal opinion is:


1. In the application, if it runs in the background for a long time and does not need interaction, use the service.

The same is in the background, without interaction, if only to complete a task, then it does not need to run, and may be multiple tasks, need to run for a long time using threads.


2. If tasks take up too much CPU time and resources, threads should be used.


On the Stopping Mode of Services

                  stopSelf();//When the first thread finishes executing, the service stops.

            //All threads are executed before the service stops.
            stopSelf(startId);


There are obvious differences in use.


Services can also inherit another class of IntentService to compensate for the shortcomings of threads.


import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

/**
 * @author Zking-Snail
 * @time 2017/2/10 20:05
 * @Version ${REV}
 */
public class MyServices2 extends IntentService {
       //Customize a parameterized construction method to implement a parameterized construction method
    public MyServices2() {
        super("");
    }

    public MyServices2(String name) {
        super(name);
    }

    //Similar to: onStartCommand in Service
    @Override
    protected void onHandleIntent(Intent intent) {
        for (int i = 0; i <10 ; i++) {
            Log.i("test","i="+i);
            SystemClock.sleep(200);
        }
    }
}


IntentService does not require additional threads to perform time-consuming operations as opposed to inheriting Service, and inherits IntentService classes when closing the service


Threads will be closed in turn in the order they are opened!


Similar to broadcasting, it should also be declared in the manifest file.


        <service android:name=".MyServices2"
            android:exported="true"//Make services executable
            ></service>
    </application>

Maybe I'm not good enough. Don't spray if you don't like it.


Posted by Zssz on Tue, 26 Mar 2019 14:24:30 -0700