Android基础-08

Android基础-08 广播与服务

01_start开启服务的生命周期(重点)

服务的特点:

生命周期的回调方法:

onCreate: 初始化service的实例对象;
onStartCommand:开启服务;
onDestroy:销毁实例对象之前调用这个方法做扫尾工作;
onResume、onPause、onStop、onRestart等生命周期的都没有,因为没有界面;

02_bind方式开启服务的生命周期(重点)

使用的方法:

bindService:绑定服务、开启服务;
unbindService:解除绑定的服务、停止服务;

特点:

1、第一次绑定服务时,先创建一个服务对象oncreate,然后绑定服务onBind;
2、解除绑定的服务时,先解除绑定服务,然后销毁服务的实例对象;
3、服务只能被帮顶一次,多次绑定不会执行任何操作;
4、服务只能接触一次,如果多次解除绑定程序会抛出异常;
5、当界面关闭时,服务就被解除绑定了;

推荐的混合开启服务的方式:

1、startService:使用这种方式开启服务,可以让服务长期运行在后台;
2、bindService:绑定服务,为了调用服务里面的业务逻辑方法;
3、unbindService:解除绑定,为了不再调用服务里面的业务逻辑方法;
4、stopService:停止服务,不再使用服务对象;

03_为什么要引入bindservice的API

目的:为了让应用程序能够调用服务里面的业务逻辑方法;

04_绑定服务调用服务方法的过程

步骤 :

1、在服务的类里面写中间人的内部类,让它IBinder接口,目的是为onBind返回中间人这个类型:
2、在中间人内部写一个方法,在这个方法里面调用服务处的业务逻辑方法:
3、在activity中绑定服务成功时,得到中间人的对象;
4、在activity中调用中间人的方法,就相当于间接地调用服务的业务逻辑方法:

代码:

TestService.java:

package com.itheima.testservice;

import java.io.FileDescriptor;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.widget.Toast;

public class TestService extends Service {

    /**
     * 应用程序绑定服务对象时会调用这个方法
     * 绑定服务
     */
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("--------onBind-----------");
        //绑定服务时返回中间人对象
        return new MyBinder();
    }

    /**
     * 
     * 解除绑定的服务时调用这个方法
     */
    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("--------onUnbind-----------");
        return super.onUnbind(intent);
    }


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

        System.out.println("--------onCreate-----------");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("--------onStartCommand-----------");
        return super.onStartCommand(intent, flags, startId);
    }

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

    /**
     * 服务的业务逻辑方法
     */
    public void methodInService() {
        System.out.println("=======methodInService==================");
        Toast.makeText(this, "tishi", 0).show();
    }


    /**
     * 1、中间人
     * @author Administrator
     *
     */
    public  class MyBinder extends Binder{

        //2、在中间人内部写一个方法,在这个方法里面调用服务处的业务逻辑方法:
        public void callMethodInService(){
            //调用服务的业务逻辑方法
            methodInService();
        }


    }
}

MainActivity.java:

package com.itheima.testservice;

import com.itheima.testservice.TestService.MyBinder;

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;

public class MainActivity extends Activity {

    private Intent intent;
    private MyConn conn;
    private MyBinder myBinder;

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

    public void start(View view) {

        intent = new Intent(this, TestService.class);

        startService(intent);
    }

    public void stop(View view) {

        stopService(intent);
    }

    public void call(View view){

        //4、在activity中调用中间人的方法,就相当于间接地调用服务的业务逻辑方法:
        myBinder.callMethodInService();
    }

    public void bind(View view) {
        intent = new Intent(this, TestService.class);

        conn = new MyConn();
        //intent 开启service使用的intent
        //MyConn 应用程序与服务之间建立的连接
        //开启服务时如果服务对象不存在,就会自动创建一个服务对象
        bindService(intent,conn, BIND_AUTO_CREATE);
    }

    public void unbind(View view) {
        //解除绑定的服务
        unbindService(conn);
    }


    private class MyConn implements ServiceConnection {



        /**
         * 绑定服务成功会调用这个方法 让应用程序与service之间建立一个连接,就是通讯的通道
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            myBinder = (MyBinder) service;
        }

        /**
         * 服务的连接崩溃的时候调用这方方法
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

    }

}

05_绑定服务抽取接口(重点)

接口的作用:对外暴露功能,隐藏实现的细节;

步骤:

1、在工程里面添加一个接口,里面写一个方法,对外开放的方法:
2、让中间人实现这个接口,为了让中间人具有接口的角色(类型),中间人需要实现接口里面的方法;
3、在activity中绑定服务成功时得到接口类型的对象;
4、在activity中调用接口类型的中间人的方法;

代码:

IService.java:

package com.itheima.testservice.service;

public interface IService {
    public void callMethodInService();
}

TestService.java:

package com.itheima.testservice;

import com.itheima.testservice.service.IService;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.view.View;
import android.widget.Toast;

public class TestService extends Service {

    /**
     * 应用程序绑定服务对象时会调用这个方法
     * 绑定服务
     */
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("--------onBind-----------");
        //绑定服务时返回中间人对象
        return new MyBinder();
    }

    /**
     * 
     * 解除绑定的服务时调用这个方法
     */
    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("--------onUnbind-----------");
        return super.onUnbind(intent);
    }


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


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("--------onStartCommand-----------");
        return super.onStartCommand(intent, flags, startId);
    }

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

    /**
     * 服务的业务逻辑方法
     */
    public void methodInService() {
        System.out.println("=======methodInService==================");
        Toast.makeText(this, "tishi", 0).show();
    }

    public void eat(){
        System.out.println("=======eat==================");
    }

    public void nj(){
        System.out.println("=======nj==================");
    }

    public void xsn(){
        System.out.println("=======xsn==================");
    }

    /**
     * 1、中间人
     * @author Administrator
     *
     */
    private  class MyBinder extends Binder implements IService{

//      //2、在中间人内部写一个方法,在这个方法里面调用服务处的业务逻辑方法:
//      public void callMethodInService(){
//          //调用服务的业务逻辑方法
//          methodInService();
//      }

        public void callEat(){
            eat();
        }

        public void callXsn(){
            xsn();
        }

        /**
         * 2、实现接口中的方法,在这方法里面调用服务的业务逻辑方法
         */
        @Override
        public void callMethodInService() {
            //调用服务的业务逻辑方法
            methodInService();
        }
    }
}

MainActivity.java:

package com.itheima.testservice;

import com.itheima.testservice.service.IService;
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;

public class MainActivity extends Activity {

    private Intent intent;
    private MyConn conn;
//  private MyBinder myBinder;
    private IService myBinder;

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

    public void start(View view) {
        intent = new Intent(this, TestService.class);
        startService(intent);
    }

    public void stop(View view) {
        stopService(intent);
    }

    public void call(View view) {
        // 4、在activity中调用中间人的方法,就相当于间接地调用服务的业务逻辑方法:
        myBinder.callMethodInService();
    }

    public void bind(View view) {
        intent = new Intent(this, TestService.class);
        conn = new MyConn();
        // intent 开启service使用的intent
        // MyConn 应用程序与服务之间建立的连接
        // 开启服务时如果服务对象不存在,就会自动创建一个服务对象
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    public void unbind(View view) {
        // 解除绑定的服务
        unbindService(conn);
    }

    private class MyConn implements ServiceConnection {
        /**
         * 绑定服务成功会调用这个方法 让应用程序与service之间建立一个连接,就是通讯的通道
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//          myBinder = (MyBinder) service;
            //3、在activity中绑定服务成功时得到接口类型的对象;
            myBinder = (IService) service;

        /**
         * 服务的连接崩溃的时候调用这方方法
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }
}

06_服务的应用场景

应用场景:天气预报、股票软件,检测网络状态提交数据;

07_利用服务注册广播接收者

使用代码注册广播接收者的目的:有些操作比较频繁的广播事件,如果使用配置文件来注册,每次在接收广播事件的时候都需要读取配置,这样比较耗时并且占用的资源比较大。如果使用代码注册广播接收者会比较省时和节省资源。

模版代码:

//1、创建广播接收者的对象
ScreenBroadcastReceiver receiver = new ScreenBroadcastReceiver();
//2、创建IntentFilter
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.SCREEN_OFF");
filter.addAction("android.intent.action.SCREEN_ON");
//3、注册广播接收者
registerReceiver(receiver, filter);

08_远程服务aidl的写法(重点)

远程服务:在同一个设备安装的另一个应用程序,在这应用程序中有一个服务在运行。
本地服务:服务的类是写在当前应用程序里面的。

在本地的应用程序中调用另一个工程里面的服务的方法。

aidl:Android Interface Definition Language 安卓的接口定义语言;
aidl格式的文件都是对外开放的共享文件,可以把它拷贝到其他工程里使用;

IPC:Inter Process communication进程间的通讯;

步骤:

1、在远程工程里面添加一个接口,里面写一个方法,对外开放的方法:
2、让中间人实现这个接口,为了让中间人具有接口的角色(类型),中间人需要实现接口里面的方法:
    修改IService接口的扩展名为aidl,为了写一个对外开放的共享文件,让中间人继承Stub;
3、在本地应用程序的activity中绑定服务成功时得到接口类型的对象:
    在本地工程中创建了一个与远程服务工程一样的包,把aidl文件拷贝到这个包里;
4、在本地应用程序activity中绑定服务成功时得到IService接口类型的中间人对象:

远程服务:

package com.itheima.remoteservice;

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

import com.itheima.remoteservice.IService.Stub;

public class TestService extends Service {

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


    public void methodInService(){
        System.out.println("----------methodInService----------");
    }


    private class MyBinder extends Stub{

        /**
         * 实现接口中的方法
         */
        @Override
        public void callMethodInService() {
            //调用了服务的业务逻辑方法
            methodInService();
        }
    }

}

本地应用程序代码:

package com.itheima.localapp;

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.os.RemoteException;
import android.view.View;

import com.itheima.remoteservice.IService;
import com.itheima.remoteservice.IService.Stub;

public class MainActivity extends Activity {

    private Intent intent;
    private MyConn conn;

    private IService myBinder;

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

    public void start(View view) {

        intent = new Intent();
        intent.setAction("com.itheima.remoteservice.REMOTESERVICE");
        startService(intent);
    }

    public void bind(View view) {

        conn = new MyConn();
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    public void unbind(View view) {

        unbindService(conn);
    }


    public void stop(View view) {

        stopService(intent);
    }

    public void call(View view){
        try {
        //调用接口的方法,间接地调用服务的业务逻辑方法
            myBinder.callMethodInService();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private class MyConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //得到IService接口类型的对象
            myBinder = Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }
    }
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。