Android 之路55---四大组件之Service

本文深入探讨了Android中服务(Service)的使用方式,包括启动、停止、绑定及解绑等核心操作,并通过实例展示了如何利用服务执行后台任务,如循环线程与进度监控。

导读

1.简介
2.两种服务的使用

简介

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

两种服务的使用

这里写图片描述

说明:接下来的案例运用了两种服务,其中1~100循环线程是与Activity无关的,而与打印线程进度是需要绑定的

这里写图片描述

配置文件 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hala.srevicedemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

布局文件 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    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.hala.srevicedemo.MainActivity">

   <Button
       android:id="@+id/start"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="启动服务"
       android:onClick="onClick"/>

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停止服务"
        android:onClick="onClick"/>

    <Button
        android:id="@+id/bind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="绑定服务"
        android:onClick="onClick"/>

    <Button
        android:id="@+id/unbind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="解锁服务"
        android:onClick="onClick"/>

</LinearLayout>

MainActivity.java

package com.hala.srevicedemo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private ServiceConnection conn=new ServiceConnection() {
        //当客户端正常连接着Service时,执行服务的绑定操作会被调用
        //如果没有ServiceConnection,会出现绑定后解绑,无法再次绑定的情况
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("TAG","hello,bind again");
            //强制转换
            MyService.MyBinder mb=(MyService.MyBinder)service;
            int step=mb.getProcess();
            Log.d("TAG","当前进度为:"+step);
        }

        //当客户端和服务的连接丢失了
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


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

    public void onClick(View view){

        //start 与 stop为一组
        //bind 与 unbind为一组
        switch (view.getId()){
            case R.id.start:
                //如果服务已经创建,重复启动不会重新创建,操作的是同一个服务,除非先销毁
                Intent it=new Intent(this,MyService.class);
                startService(it);
                break;

            case R.id.stop:
                //这里虽然是两个intent,但确实针对同一个对象
                Intent it1=new Intent(this,MyService.class);
                stopService(it1);
                break;

            case R.id.bind:
                //绑定服务:最大作用是对Service执行的任务进行监控,如下载到哪了,音乐播放到哪了
                Intent it2=new Intent(this,MyService.class);
                bindService(it2,conn,BIND_AUTO_CREATE);
                break;

            case R.id.unbind:
                //要指明解绑哪个连接,所以conn要设置为全局
                unbindService(conn);
                break;
        }

    }
}

MyService.java

package com.hala.srevicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

//实现进度监控(两个要素):
//ServicerConnection:用与绑定客户端和Service->见MainActivity.java有说明
//IBinder:在android中用于远程操作对象的一个基本接口
//因为IBinder强制要求我们实现一些方法,而Binder类是给所有强制方法实现了一个空方法
//在开发中我们会自己写一个内部类,继承Binder类,在里边写自己的方法
public class MyService extends Service {

    public static final String TAG = "TAG";
    private int i;

    public MyService() {
    }

    /**
     * 创建
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG,"服务创建了");
        //开启一个线程,模拟耗时任务
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                for(i = 0; i <100; i++){
                        sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 启动
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG,"服务启动了");
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 绑定
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.e(TAG,"服务绑定了");
        return new MyBinder();

    }

    class MyBinder extends Binder{
        public int getProcess(){
            return i;
        }

    }

    /**
     * 解绑
     * @param intent
     * @return
     */
    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG,"服务解绑了");
        return super.onUnbind(intent);
    }

    /**
     * 销毁
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG,"服务销毁了");
    }
}

显示结果

这里写图片描述

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值