绑定/解除绑定服务示例 (android) [英] bind/unbind service example (android)

查看:43
本文介绍了绑定/解除绑定服务示例 (android)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能给我举个简单的例子,说明一个带有后台服务的应用程序,它使用绑定/解除绑定方法来启动和停止它吗?我在谷歌上搜索了半个小时,但这些示例使用了 startService/stopService 方法,或者对我来说非常困难.谢谢.

can you give me a simple example of an application with background service which uses bind/unbind methods to start and stop it? I was googling for it for a half-hour, but those examples use startService/stopService methods or are very difficult for me. thank you.

推荐答案

您可以尝试使用以下代码:

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

这篇关于绑定/解除绑定服务示例 (android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆