安卓Service(二)

本文详细介绍了Android中的Service启动方式,重点讲解了bindService的特点、使用步骤,以及IntentService的优势和使用实例。bindService允许直接操作Service对象,但使用较复杂;IntentService简化了线程管理,适合进行耗时操作,但无法精确控制执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.Service有几种启动方式
Service有二种启动方式,一种就是我上次写的startService,另一种是bindService。下面将主要介绍bindService以及IntentService(一种新的类,并不是启动方式)。
二.startService的特点及优缺点
优点:startService使用简单,和Activity一样,只要几行代码就能启动Service。
缺点:startService无法获得Service对象,不能直接操作Service中的属性和方法,只能通过Intent传值,重复调用startService,触发onStartComment。
三.bindService的特点及优缺点
优点:可以得到Service对象,灵活控制Service内部的属性和方法。
缺点:使用方法复杂。
四.bindService使用实例
这里先介绍bindService方式
1.新建类继承Servic
2.重写onCreate方法
3.实现onBind方法
4.重写onUnBind方法
5.重写onDestroy方法
6.在AndroidManifest中注册Service
7.在有Context环境中实现ServiceConnection接口。
8.在有Context环境中通过bindService绑定Service。
9.在有Context环境中通过unbindService解绑Service。
代码展示
先创个类继承Service

package com.example.ll.storeapplication.store;

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

/**
 * Created by ll on 2018/3/23.
 */

public class TextService  extends Service{

    private   String Tag="TextService";

    private  Guanjia guanjia=new Guanjia();

    public  class  Guanjia extends Binder{
        //作用:得到当前Service对象
        public  TextService getServiceObject(){
            return  TextService.this;
        }

    }

    public  void  fly(){
        Log.e(Tag,"开飞机.......");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(Tag,"onBind.......");

        return guanjia;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(Tag,"onUnbind.......");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(Tag,"onCreate.......");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(Tag,"onDestroy.......");
    }

}

然后写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.ll.storeapplication.ServiceActivity">

    <Button
        android:id="@+id/bindbtn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="绑定SERVICE" />

    <Button
        android:id="@+id/jiebanbtn"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="解绑SERVICE" />

    <Button
        android:text="跳转B界面"
        android:id="@+id/diaozhuan"
        android:layout_width="match_parent"
        android:layout_height="50dp" />
</LinearLayout>

最后在主要Activity写启动Service

package com.example.ll.storeapplication;

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.view.View;
import android.widget.Button;

import com.example.ll.storeapplication.store.TextService;

public class ServiceActivity extends AppCompatActivity implements View.OnClickListener{
private Button jbbtn;
private  Button bdbtn;
private  Button tzbtn;
private ServiceConnection serviceConnection=new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        //通过管家的中介作用,拿到TextService对象
        TextService textService=((TextService.Guanjia) iBinder).getServiceObject();
        textService.fly();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

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

        bindId();
    }

    private void bindId() {
        jbbtn=findViewById(R.id.bindbtn);
        bdbtn=findViewById(R.id.jiebanbtn);
        jbbtn.setOnClickListener(this);
        bdbtn.setOnClickListener(this);
        tzbtn=findViewById(R.id.diaozhuan);
        tzbtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bindbtn:
                Intent intent=new Intent(this,TextService.class);
                bindService(intent,serviceConnection,BIND_AUTO_CREATE);
                break;
            case R.id.jiebanbtn:
                unbindService(serviceConnection);
                break;
            case R.id.diaozhuan:
                Intent intent1=new Intent(this,BActivity.class);
                startActivity(intent1);
                break;
        }
    }
}

五.IntentService优点和缺点
优点:无需处理线程的创建与线程同步问题,无需手动关闭Service。
缺点:无法精准控制线程执行过程,一旦启动只能等待线程结束。
六.IntentService使用实例
首先了解IntentService的步骤
1.兴建类继承IntentService
2.实现父类的构造方法
3.重写onHandleIntent方法
4.重写onCreate方法
5.重写onDestroy方法
6.在在AndroidManifest中注册Service
7.在有Context环境中通过startService启动Service
代码展示
先创个类继承Service

package com.example.ll.storeapplication.store;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by ll on 2018/3/23.
 */

public class MyIntentService extends IntentService {
    public MyIntentService(String name) {
        super(name);
    }
    public MyIntentService(){
        super("");

    }
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        for (int i=0;i<10;i++){
            try {
                Log.e("MyIntentService",i+"*******");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

然后写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.ll.storeapplication.IntentServiceActivity">
<Button
    android:id="@+id/oepnbtn"
    android:text="启动IntentService"
    android:layout_width="match_parent"
    android:layout_height="50dp" />
    <Button
        android:id="@+id/closebtn"
        android:text="关闭IntentService"
        android:layout_width="match_parent"
        android:layout_height="50dp" />
</LinearLayout>

最后在主要Activity写启动Service

package com.example.ll.storeapplication;

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

import com.example.ll.storeapplication.store.MyIntentService;

public class IntentServiceActivity extends AppCompatActivity implements View.OnClickListener{
private Button openbtn;
private  Button closebtn;
private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_service);

        bindId();
    }

    private void bindId() {
        openbtn=findViewById(R.id.oepnbtn);
        closebtn=findViewById(R.id.closebtn);
        openbtn.setOnClickListener(this);
        closebtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.oepnbtn:
                intent=new Intent(this, MyIntentService.class);
                startService(intent);
                break;
            case R.id.closebtn:
                stopService(intent);
                break;
        }

    }
}

最后完成一个读秒操作如下图
这里写图片描述
七.IntentService和Service区别
IntentService与Service最大的区别是IntentService本身自带子线程,而Service需要调用Thread方法构造子线程。所以IntentService可以直接进行耗时操作,而Service不能进行耗时操作,因为Service并不是个线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值