Android基本组件之服务Service

Service的开启与关闭

1.继承Service类
2.在AndroidManifest.xml中注册
<service android:name=".MyService" android:enabled="true" android:exported="true"></service>
直接创建Service的话,前两步会自动执行
3.通过Contex.startService()或Contex.bindService()启动服务

Intent startIntent = new Intent(this,MyService.class);
startService(startIntent);

通过startService()方法启动的服务于调用者没有关系,即使调用者关闭了,服务仍然运行,想停止服务要调用Context.stopService(),此时系统会调用onDestory(),使用此方法启动时,服务首次启动系统先调用服务的onCreate()–>onStart(),如果服务已经启动再次调用只会触发onStart()方法。

Service与Activity之间的通信

MyService.xml

package com.example.servicetest;

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

public class MyService extends Service {
    String TAG = "MyService";
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG,"start service");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"destroy service");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return  new MyBinder();
    }

    public static class MyBinder extends Binder{
        public void startDownload() {
            Log.d("Debug", "startDownload()");
        }
    }
}

MainActivity.java

package com.example.servicetest;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button start_Button;
    Button destroy_Button;
    Button bind_Button;
    Button unbind_Button;
    MyService myService = new MyService();
    MyService.MyBinder myBinder = new MyService.MyBinder();
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder =(MyService.MyBinder) service;
            Log.d("Debug","Connection");
            myBinder.startDownload();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start_Button = findViewById(R.id.start_service);
        start_Button.setOnClickListener(this);
        destroy_Button = findViewById(R.id.destroy_service);
        destroy_Button.setOnClickListener(this);
        bind_Button = findViewById(R.id.bind);
        bind_Button.setOnClickListener(this);
        unbind_Button = findViewById(R.id.unbind);
        unbind_Button.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start_service:
                Intent startIntent = new Intent(this,MyService.class);
                startService(startIntent);
                Toast.makeText(MainActivity.this,"start",Toast.LENGTH_SHORT).show();
                break;
            case R.id.destroy_service:
                Intent stopIntent = new Intent(this,MyService.class);
                stopService(stopIntent);
                Toast.makeText(MainActivity.this,"destroy",Toast.LENGTH_SHORT).show();
                break;
            case R.id.bind:
                Intent bind = new Intent(this,MyService.class);
                bindService(bind,connection,BIND_AUTO_CREATE);
                Log.d("Debug","bind");
                break;
            case R.id.unbind:
                Log.d("Debug","unbind");
                unbindService(connection);
                break;
            default:
                break;
        }
    }
}

布局文件

<?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=".MainActivity">

    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Start service"/>

    <Button
        android:id="@+id/destroy_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Destroy service"/>

    <Button
        android:id="@+id/bind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Bind"/>

    <Button
        android:id="@+id/unbind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Unbind"/>

</LinearLayout>

流程如下:

(1) 新建MyService,重写onBind方法,新建内部类MyBinder

(2)在Activity中新建ServiceConnection匿名类,重写类中的两个方法

(3)在Activity中BindServic这个Button的onClick方法中调用了bindService这个方法,使得Activity和Service进行绑定。

注:
(1)为了使Activity能控制Service,Activity中必须有Service的实例。

当Activity与Service进行绑定的时候会调用ServiceConnection.onServiceConnected()方法,在这个方法中会回调Service的onBind()方法,进而在Activity中得到MyService中的Binder,这样就能在Activity中获得了Service的实例。

(2)ServiceConnection.onServiceDisconnected()

当Service崩溃或者被kill的时候调用,当客户端解除绑定的时候,不调用。

(3)使用bindService()启动的服务与调用者绑定,只要调用者关闭服务就终止。

使用此方法启动时,服务首次启动系统先调用服务的onCreate()–>onBind(),如果服务已经启动再次调用不会再触发这2个方法,调用者退出时系统会调用服务的onUnbind()–>onDestory(),想主动解除绑定可使用Contex.unbindService(),系统依次调用onUnbind()–>onDestory()。在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值