Android Service的基本用法(1)

Service作为android四大组件之一,在应用程序中都要用到它。它主要用于在后台处理一些耗时的逻辑,或者去执行某些需要长期运行的任务。

Android Service生命周期


Service的用法

Android Studio 新建一个Android项目,然后右击选择 new Service

Android Studio 会自动添加一个类继承自Service 并且在AndroidManifest.xml中进行了注册
Service 注册在application 里面
<service
    android:name=".MyService"
    android:enabled="true"
    android:exported="true"></service>
然后重写onCreate()、onStartCommand()和onDestroy()方法,代码如下所示;
package com.example.administrator.myapplication_service;


import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.util.Log;

/*
    Service同时只会被创建一次在停止前一直会在后台运行
    启动service的时候onCreate()方法只有第一次会调用,onStartCommand()和onStart()每次都被调用
    启动服务:Activity调用 startService() 来启动服务
    停止服务:Activity调用  stopService() 来停止服务 或者Service本身调用 stopSelf()
    一个已经启动的Service会调用 onStartCommand() 来执行业务
    Service默认跟主线程在同一线程中执行,当Service执行耗时的操作时会阻塞主线程 所以要用子线程来操作
 */
public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("MyService onCreate");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        for(int i=0;i<10;i++){
            System.out.println("MyService onStartCommand"+i);
            if(i>5){
           //     stopSelf();
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

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

    @Override
    public void onDestroy() {
        System.out.println("MyService onDestroy");
        super.onDestroy();
    }
}
然后打开activity_main.xml程序的主布局文件,代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.administrator.myapplication_service.MainActivity">


    <RelativeLayout
        android:layout_width="368dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/button3"
            android:layout_width="368dp"
            android:layout_height="wrap_content"
            android:text="开启服务"
            android:onClick="startService"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="30dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="21dp" />

        <Button
            android:id="@+id/button4"
            android:layout_width="368dp"
            android:layout_height="wrap_content"
            android:text="关闭服务"
            android:onClick="stopService"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="122dp"
            android:layout_below="@+id/button3"
            android:layout_alignParentStart="true"
            android:layout_marginTop="39dp" />

    </RelativeLayout>
</android.support.constraint.ConstraintLayout>
在布局文件中加入了两个按钮,一个用于启动Service,一个用于停止Service。
然后打开MainActivity主Activity,在里面加入启动Service和停止Service的逻辑,代码如下所示:
package com.example.administrator.myapplication_service;

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

public class MainActivity extends AppCompatActivity {

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

    public void  startService(View v){
        //启动服务
        Intent intent=new Intent(MainActivity.this,MyService.class);
        startService(intent);
    }
    public void  stopService(View v){
        //停止服务
        Intent intent=new Intent(MainActivity.this,MyService.class);
        stopService(intent);
    }
}

在Start Service按钮的点击事件里,新建一个Intent对象,并调用startService()方法来启动MyService。
然后在Stop Serivce里,同样新建一个Intent对象,并调用stopService()方法来停止MyService。
一个简单的Serivce就写好了,我们来Run一下

连续点击了两次“开启服务”可以发现onCreate()只执行了一次,而onStartCommand()执行了两次,点击“关闭服务”Service就被
Destroy()掉了。
哪里不对的地方大神轻喷(⊙ᗜ⊙)


猜你喜欢

转载自blog.csdn.net/ripndip/article/details/73612507
今日推荐