四大组件---Service初步认识

引用了:https://blog.csdn.net/javazejian/article/details/52709857
引用了:http://linkinmama-gmail-com.iteye.com/blog/1569039
引用了:https://blog.csdn.net/iromkoear/article/details/63252665

Service疑问

Activity与Service是否处于同一进程?

一般来说:同一个包内的activity和service,如果service没有设定属性android:process=":remote"的话,service会和activity跑在同一个进程中,由于一个进程只有一个UI线程,所以,service和acitivity就是在同一个线程里面的。android:process=":remote"值得注意他的用法!!!如果Activity想访问service中的对象或方法,如果service设定属性android:process=":remote",那么就是跨进程访问,跨进程访问容易出现意想不到的问题,还是慎重给service设定属性android:process=":remote"

Service 的两大功能是什么?怎样实现?
android系统中的Service主要有两个作用:后台运行和跨进程通讯。
情况1:当Acitivity和Service处于同一个Application和进程时,通过继承Binder类来实现。

步骤如下:
Service和Activity的连接可以用ServiceConnection来实现,需要实现一个新的ServiceConnection,重写onServiceConnected和onServiceDisconnected方法。执行绑定,调用bindService方法,传入一个选择了要绑定的Service的Intent(显式或隐式)和一个你实现了的ServiceConnection实例。一旦连接建立,你就能通Service的接口onBind()得到serviceBinder实例进而得到Service的实例引用。一旦Service对象找到,就能得到它的公共方法和属性。但这种方式,一定要在同一个进程和同一个Application里。

情况2:跨进程通讯,使用AIDL;

步骤如下:
1. 在Eclipse工程的package目录中建立一个扩展名为aidl的文件。package目录就是Java类所在的目录。该文件的语法类似于Java代码。aidl文件中定义的是AIDL服务的接口。这个接口需要在调用AIDL服务的程序中访问。
2. 如果aidl文件的内容是正确的,Eclipse插件会自动生成一个Java接口文件(*.java)。
3. 建立一个服务类(Service的子类)。
4. 实现由aidl文件生成的Java接口。
5. 在AndroidManifest.xml文件中配置AIDL服务,尤其要注意的是,<action>标签的android:name属性值就是客户端要引用该服务的ID,也就是Intent类构造方法的参数值。

Service说明

1.startService 启动 一旦启动,只要不手动停止,不会停止

如果运行在后台的Service不需要和展示内容进行交互,这种情况下,一般是调用startService来启动Service。比如播放音乐。
startService启动,start生命周期
Intent intent = new Intent(Main.this, MyService.class);
startService(intent);
无标题.png
stopService停止,stop生命周期
Intent intent = new Intent(Main.this, MyService.class);
stopService(intent);

或者 service中使用

stopSelf();
无标题.png
如果多次start,之后stop
无标题.png

总结:服务不会被多次创建新的

提示
1.onStart()

onStart方法是在Android2.0之前的平台使用的.

2.onStartCommand()

在2.0及其之后,则需重写onStartCommand方法,

3.备注:

同时,旧的onStart方法则不会再被直接调用(外部调用onStartCommand,而onStartCommand里会再调用 onStart。在2.0之后,推荐覆盖onStartCommand方法,而为了向前兼容在onStartCommand依然会调用onStart方法。

演示(播放音乐,并循环)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    System.out.println("startCommand");
    final MediaPlayer player = new MediaPlayer().create(this, R.raw.weidao);
    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            player.start();
        }
    });
    player.start();
    return super.onStartCommand(intent, flags, startId);
}

2.bindService 启动,一般需要交互时使用

启动周期
绑定代码
Intent intent = new Intent(Main.this, MyService.class);
serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {}

    @Override
    public void onServiceDisconnected(ComponentName componentName) {}
};
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
解绑代码
unbindService(serviceConnection);
1.(非正常)绑定 但不解绑 直接退出activity(bind)
生命周期
无标题1.png
2.(正常) 正常绑定 正常解绑(bind unbind)
生命周期
无标题1.png
3.(非正常) startService bindService stopService unBindService(先启动 再绑定)
无标题1.png

总结:不会创建多个service,并且stop无效,只能unbind销毁

4.(非正常) bindService startService stopService unBindService(先绑定 再启动)
无标题.png

总结:不会创建多个service,并且stop无效,只能unbind销毁

5.(非正常)bindService bindService unBindService(多次绑定)
无标题1.png

总结:多次绑定只会执行一次 bind

注意
1.说明

因为如果没有bind 或者 已经断开bind 这个时候如果解绑 应用就会报错崩溃

2.代码演示
第一种方法(如果你的SerVice的onBind返回值为空____不会执行onServiceConnected)
private boolean isBinded = false;
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    isBinded = true;
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
    isBinded = false;
}
if (isBinded){
    unbindService(serviceConnection);
    isBinded = false;
}
第二种方法
try{
    unbindService(serviceConnection);
}catch(Exception e){
    System.out.println("解绑出错");
}

服务Service与线程Thread的区别

转自头部引用1
  • 两者概念的迥异

    • Thread 是程序执行的最小单元,它是分配CPU的基本单位,android系统中UI线程也是线程的一种,当然Thread还可以用于执行一些耗时异步的操作。

    • Service是Android的一种机制,服务是运行在主线程上的,它是由系统进程托管。它与其他组件之间的通信类似于client和server,是一种轻量级的IPC通信,这种通信的载体是binder,它是在linux层交换信息的一种IPC,而所谓的Service后台任务只不过是指没有UI的组件罢了。

  • 两者的执行任务迥异

    • 在android系统中,线程一般指的是工作线程(即后台线程),而主线程是一种特殊的工作线程,它负责将事件分派给相应的用户界面小工具,如绘图事件及事件响应,因此为了保证应用 UI 的响应能力主线程上不可执行耗时操作。如果执行的操作不能很快完成,则应确保它们在单独的工作线程执行。

    • Service 则是android系统中的组件,一般情况下它运行于主线程中,因此在Service中是不可以执行耗时操作的,否则系统会报ANR异常,之所以称Service为后台服务,大部分原因是它本身没有UI,用户无法感知(当然也可以利用某些手段让用户知道),但如果需要让Service执行耗时任务,可在Service中开启单独线程去执行。

  • 两者使用场景

    • 当要执行耗时的网络或者数据库查询以及其他阻塞UI线程或密集使用CPU的任务时,都应该使用工作线程(Thread),这样才能保证UI线程不被占用而影响用户体验。

    • 在应用程序中,如果需要长时间的在后台运行,而且不需要交互的情况下,使用服务。比如播放音乐,通过Service+Notification方式在后台执行同时在通知栏显示着。

  • 两者的最佳使用方式

    在大部分情况下,Thread和Service都会结合着使用,比如下载文件,一般会通过Service在后台执行+Notification在通知栏显示+Thread异步下载,再如应用程序会维持一个Service来从网络中获取推送服务。在Android官方看来也是如此,所以官网提供了一个Thread与Service的结合来方便我们执行后台耗时任务,它就是IntentService,(如果想更深入了解IntentService,可以看博主的另一篇文章:Android 多线程之IntentService 完全详解),当然 IntentService并不适用于所有的场景,但它的优点是使用方便、代码简洁,不需要我们创建Service实例并同时也创建线程,某些场景下还是非常赞的!由于IntentService是单个worker thread,所以任务需要排队,因此不适合大多数的多任务情况。

  • 两者的真正关系

    • 两者没有半毛钱关系。

StartService 使用

记得AndroidManifest注册
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.widget.RemoteViews;

import static android.app.Notification.FLAG_ONGOING_EVENT;

/**
 * Created by rtyui on 2018/4/17.
 */

public class MyService extends Service {

    //关于notifacation
    private NotificationManager manager;
    public static final String id = "channel_1";
    public static final String name = "channel_name_1";
    private RemoteViews remoteViews;
    private Notification notification;

    //播放
    private MediaPlayer player;
    private MyReceiver myReceiver;

    @Override
    public void onCreate() {
        manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("onBind");
        return null;
    }


    //开启
    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        registReceiver();
        super.onStart(intent, startId);
        player = new MediaPlayer().create(this,R.raw.weidao);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                if (player != null)
                    player.start();
            }
        });
        player.start();
        new Thread(new MyThread()).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(myReceiver);
        super.onDestroy();
    }

    //发送notification
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void sendNotification(int progress){
        if (notification == null)
            initNotification();
        remoteViews.setProgressBar(R.id.pro, 100, progress, false);
        manager.notify(1,notification);
    }

    //初始化notification
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void initNotification(){
        NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
        manager.createNotificationChannel(channel);
        remoteViews=new RemoteViews(getPackageName(), R.layout.music_pro);
        notification = new Notification.Builder(this, id)
                .setContentTitle("we")
                .setContentText("wewe")
                .setShowWhen(false)
                .setPriority(Notification.PRIORITY_MAX)
                .setSmallIcon(android.R.drawable.stat_notify_more)
                .setAutoCancel(false).build();
        notification.contentView = remoteViews;
        notification.flags = FLAG_ONGOING_EVENT;
        Intent intent = new Intent();
        intent.setAction("100027");
        remoteViews.setOnClickPendingIntent(
                R.id.btn, PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)
        );
        sendNotification(0);
    }

    //注册广播
    private void registReceiver(){
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("100027");
        intentFilter.addAction("100002");
        registerReceiver(myReceiver, intentFilter);
    }

    //广播监听类
    private class MyReceiver extends MyBroadcastReceiver {
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);
            switch (intent.getAction()){
                case "100027":
                    manager.cancel(1);
                    player = null;
                    break;
                case "100002":
                    if (player != null)
                        sendNotification(player.getCurrentPosition() * 100 / player.getDuration());
                    break;
            }
        }
    }

    //播放进度线程类
    private class MyThread implements Runnable{
        @Override
        public void run() {
            while (true){
                if (player != null){
                    try {
                        Intent intent = new Intent();
                        intent.setAction("100002");
                        sendBroadcast(intent);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    System.out.println("结束");
                    break;
                }
            }
        }
    }
}

bindService 使用

记得AndroidManifest注册
interface OnMediaListener
public interface OnMediaListener {
    void onSeek(int progress);
}
service MyService1
package com.example.rtyui.androidteach;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
/**
 * Created by rtyui on 2018/4/17.
 */

public class MyService1 extends Service {
    //播放
    private MediaPlayer player;
    private OnMediaListener onMediaListener;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        player = new MediaPlayer().create(this,R.raw.weidao);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                if (player != null)
                    player.start();
            }
        });
        player.start();
        new Thread(new MyThread()).start();
        return new MyBinder();
    }

    @Override
    public void onDestroy() {
        player = null;
        super.onDestroy();
    }

    public class MyBinder extends Binder {
        public MyService1 getService(){
            return MyService1.this;
        }
    }

    public void setOnMediaListener(OnMediaListener onMediaListener) {
        this.onMediaListener = onMediaListener;
    }

    //播放进度线程类
    private class MyThread implements Runnable{
        @Override
        public void run() {
            while (true){
                if (player != null){
                    if (onMediaListener != null){
                        try {
                            onMediaListener.onSeek(player.getCurrentPosition() * 100 / player.getDuration());
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }else{
                    System.out.println("结束");
                    break;
                }
            }
        }
    }
}
Activity Main
package com.example.rtyui.androidteach;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.ProgressBar;

public class Main extends Activity {

    private ServiceConnection serviceConnection;
    private ProgressBar progressBar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        progressBar = findViewById(R.id.pro);
        serviceConnection = new ServiceConnection(){

            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                ((MyService1.MyBinder)iBinder).getService().setOnMediaListener(new OnMediaListener() {
                    @Override
                    public void onSeek(int progress) {
                        progressBar.setProgress(progress);
                    }
                });
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Main.this, MyService1.class);
                bindService(intent, serviceConnection, BIND_AUTO_CREATE);
            }
        });

        findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unbindService(serviceConnection);
            }
        });
    }
}

layout main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.rtyui.androidteach.Main">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/btn"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_stop"
        android:text="stop_service"/>
    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/pro"
        android:max="100"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"/>

</LinearLayout>

intentService

说明

IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作。
当任务执行完后,IntentService 会自动停止,不需要我们去手动结束。
如果启动 IntentService 多次,那么每一个耗时操作会以工作队列的方式在 IntentService 的 onHandleIntent 回调方法中执行,依次去执行,使用串行的方式,执行完自动结束。

使用方式

我自己的理解 一个intentService最好是执行一类特定的任务
注册方式和service类似,start启动 stop停止
自以为intentService和AsyncTask的区别是 intentService可以主动停止里边的任务。
_
service MyIntentService
public class MyIntentService extends IntentService {

    /**
     * 是否正在运行
     */
    private boolean isRunning;

    /**
     *进度
     */
    private int count;

    public MyIntentService() {
        super("MyIntentService");
    }

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

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            isRunning = true;
            count = 0;
            while (isRunning) {
                count++;
                if (count >= 3) {
                    isRunning = false;
                }
                System.out.println(count);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("onDestory");
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        System.out.println("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }
}
启动
Intent intent = new Intent(Main.this, MyIntentService.class);
startService(intent);
停止
Intent intent = new Intent(Main.this, MyIntentService.class);
stopService(intent);

intentService后续

当我连续启动三次 不关闭
无标题1.png

总结:顺序执行 自行销毁

当我连续启动两次 主动关闭
无标题.png

总结:主动关闭后,内部耗时任务自行结束

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,612评论 5 471
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,345评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,625评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,022评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,974评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,227评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,688评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,358评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,490评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,402评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,446评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,126评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,721评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,802评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,013评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,504评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,080评论 2 341

推荐阅读更多精彩内容

  • 【Android Service】 Service 简介(★★★) 很多情况下,一些与用户很少需要产生交互的应用程...
    Rtia阅读 3,134评论 1 21
  • 2.1 Activity 2.1.1 Activity的生命周期全面分析 典型情况下的生命周期:在用户参与的情况下...
    AndroidMaster阅读 3,010评论 0 8
  • 服务基本上分为两种形式 启动 当应用组件(如 Activity)通过调用 startService() 启动服务时...
    pifoo阅读 1,251评论 0 8
  • Service 一、基础知识 1、定义 服务,属于Android中的计算型组件 2、作用 提供需要在后台长期运行的...
    AndroidMaster阅读 278评论 0 0
  • 【柯信日日精进 03/27/2017 周一 第207天 丁酉年 二月三十日】 ✔静√智√勇√仁√强√礼 小结。 √...
    妈妈熊阅读 278评论 0 1