Android--Serviceb的绑定与解绑

bindService()

作用:绑定Service服务 
手动调用bindService()后,自动调用内部方法:onCreate()、onBind()

unbindService()

作用:解绑Service服务 
手动调用unbindService()后,自动调用内部方法:onCreate()、onBind()、onDestory()

简单Demo

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editData"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="这是默认信息"
        android:inputType="textPersonName"
        android:text="这是默认信息"
        android:layout_width="match_parent" />
    <Button
        android:id="@+id/btnStartService"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="开启服务"
      />

    <Button
        android:id="@+id/btnStopService"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="终止服务" />

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

    <Button
        android:id="@+id/btnUnbind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="解绑服务" />

    <Button
        android:id="@+id/btnSyncData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="同步数据" />


</LinearLayout>

MainActivity.java

package com.example.dpl.demoservice;

import android.content.ComponentName;
import android.content.Context;
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.EditText;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {

    private EditText editData;
    private MyService.Binder binder=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editData=findViewById(R.id.editData);
        findViewById(R.id.btnStartService).setOnClickListener(this);
        findViewById(R.id.btnStopService).setOnClickListener(this);
        findViewById(R.id.btnBind).setOnClickListener(this);
        findViewById(R.id.btnUnbind).setOnClickListener(this);
        findViewById(R.id.btnSyncData).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.btnStartService:
                Intent intent=new Intent(this,MyService.class);
                //传递参数
                intent.putExtra("data",editData.getText().toString().trim());
                startService(intent);
                break;
            case R.id.btnStopService:
                stopService(new Intent(this,MyService.class));
                break;
            case R.id.btnBind:
                //绑定服务
                bindService(new Intent(this,MyService.class),this, Context.BIND_AUTO_CREATE);
                break;
            case R.id.btnUnbind:
                unbindService(this);
                break;
            case R.id.btnSyncData:

                if (binder!=null){
                    binder.setData(editData.getText().toString().trim());
                }

                break;
        }
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

        binder= (MyService.Binder) service;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}

MyService.java

package com.example.dpl.demoservice;

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

public class MyService extends Service {
    private boolean running=false;
    private String data="这是默认信息";

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {   //MainActivity中onServiceConnected()方法调用

        return new Binder();
    }

    public class Binder extends android.os.Binder{   //MyService的内部类
        public void setData(String data){
            MyService.this.data=data;
        }
    }

    //在MainActivity执行完startService后执行onCreate()和该方法
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        data=intent.getStringExtra("data");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {  //service在第一次创建时调用
        super.onCreate();
        running=true;
        new Thread(){    //执行后台线程
            @Override
            public void run() {
                super.run();

                while (running){    //循环打印
                    System.out.println(data);
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public void onDestroy() {   //关闭服务
        super.onDestroy();
        running=false;
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值