AN service读code小结

本文详细介绍了Android中的Service组件,包括本地Service和远程Service的区别与应用场景。讲述了如何通过startService和bindService来启动和绑定Service,并提供了具体的代码示例。此外,还讲解了Service与Activity之间的数据交互方式。
摘要由CSDN通过智能技术生成

1、

android service 包含本地service 的和远程的service 

本地的没有复用性,直接是在本应用程序中使用;可以在后台调用,一般用来处理一个耗时的线程操作,不占用UI线程

而远程的则有复用性,可以被其他应用程序调用

2、

本地的service如果没有和activity有数据交互,则可以使用startService,stopService开启关闭服务
如果有交互,则使用bindService,unBindService

(1)startService,stopService开启关闭服务

public class CountService extends Service {

    private boolean threadDisable;

    private int count;

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

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (!threadDisable) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    count++;
                    Log.v("CountService", "Count is " + count);
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
        Log.v("CountService", "on destroy");
    }

    public int getCount() {
        return count;
    }

}


public class LocalServiceDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.startService(new Intent(this, CountService.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.stopService(new Intent(this, CountService.class));
    }
}

(2)

public interface ICountService {

    public abstract int getCount();
}

public class CountService extends Service implements ICountService {

    private boolean threadDisable;

    private int count;
    
    private ServiceBinder serviceBinder=new ServiceBinder();
    
    public class ServiceBinder extends Binder implements ICountService{
        @Override
        public int getCount() {
            return count;
        }
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (!threadDisable) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    count++;
                    Log.v("CountService", "Count is " + count);
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
        Log.v("CountService", "on destroy");
    }

    /* (non-Javadoc)
     * @see com.easymorse.ICountService#getCount()
     */
    public int getCount() {
        return count;
    }

}

public class LocalServiceDemoActivity extends Activity {

    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            countService = (ICountService) service;
            Log.v("CountService", "on serivce connected, count is "
                    + countService.getCount());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            countService = null;
        }

    };

    private ICountService countService;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.bindService(new Intent("com.easymorse.CountService"),
                this.serviceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unbindService(serviceConnection);
    }
}

3、

本地的Service数据交互可以通过一个java文件的接口A来做服务端和客户端的binder对象类型标准
具体做法:
(1)、service的建立内部类Inner继承Ibinder和接口A,实现A接口,执行业务逻辑之后,返回service类的内容
(2)、调用service的客户端activity则使用bindService之后进行连接服务,如果连上服务
则会使用ServiceConnection的两个函数作为回调函数来回馈信息
(3)、回调函数onServiceConnected(ComponentName classname, IBinder service)
此时回调回来的Ibinder对象是Inner 对象,可以直接使用实现A接口的函数,从而得到service的结果

例子请见2中(2)

PS:匿名内部类用在抽象类或者接口上,主要是因为没必要额外声明一个显示的类来继承该抽象类或者接口,而是直接使用
抽象类或者接口来声明一个对象并且实现抽象类或者接口中的抽象方法

4、

远程service
和本地的数据交互类型的service很类似,但是不再是用普通的java文件接口。
把java文件的接口A后缀名改为aidl;
具体做法(区别在步骤中说明): 
(1)、service建立内部类Inner实现ICountService.Stub接口,在该内部类实现A的抽象方法
(2)、调用service的客户端activity则使用bindService之后进行连接服务,如果连上服务
则会使用ServiceConnection的两个函数作为回调函数来回馈信息
(3)、回调函数onServiceConnected(ComponentName classname, IBinder service)
此时回调回来的Ibinder对象是Inner 对象,可以直接使用实现A接口的函数,从而得到service的结果


(4)、(3)这个步骤仍有疑问,因为看到有些code步骤(3)是这样写的
使用A接口声明的对象 A a =A.Stub.asInterface(service);


public class CountService extends Service {

    private boolean threadDisable;

    private int count;

    private ICountService.Stub serviceBinder = new ICountService.Stub() {

        @Override
        public int getCount() throws RemoteException {
            return count;
        }
    };

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

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (!threadDisable) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    count++;
                    Log.v("CountService", "Count is " + count);
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
        Log.v("CountService", "on destroy");
    }
}

private ServiceConnection serviceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        countService = (ICountService) service;
        try {
            Log.v("CountService", "on serivce connected, count is "
                    + countService.getCount());
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        countService = null;
    }

};

也有这样的

private ServiceConnection musicServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName classname, IBinder obj) {
            mService = IMediaService.Stub.asInterface(obj);
            Log.i(TAG, "ServiceConnection:::onServiceConnected mService:" + mService);
            if (mService != null) {
                try {
                    mService.setMusicStatusListener(musicStatusListener);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                musicPlayHandle.sendEmptyMessage(HANDLE_MESSAGE_SERVICE_START);
            }
        }


        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "ServiceConnection:::onServiceDisconnected mService:" + mService);
            mService = null;
        }
    };



本文章的code来自:点击打开链接 如果侵权或者任何不满,请联系我删掉

另外附上另一篇参考文章:点击打开链接2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值