2种方法启动Service_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3468 | 回复: 0   主题: 2种方法启动Service        下一篇 
java_along
注册用户
等级:上尉
经验:771
发帖:36
精华:0
注册:2014-2-17
状态:离线
发送短消息息给java_along 加好友    发送短消息息给java_along 发消息
发表于: IP:您无权察看 2014-8-3 11:36:31 | [全部帖] [楼主帖] 楼主

第一种 

startService


非常简单,之间在清单文件中注册下Service,然后在Activity中使用Intent调用Service.

Activity:
Intent intent=new Intent(this,StudentService2.class);
startService(intent);
Service:
@Override
public void onCreate() {
      super.onCreate();
      System.out.println("创建Service");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
      System.out.println("开始Service");
      return super.onStartCommand(intent, flags, startId);
}


在activity启动service后,控制台先后打印

创建Service

开始Service

第二种

bindService


主要介绍的是第二种方法,第二种方法相对于第一种方法来说实现比较复杂,当用户再Activity里绑定service后,service返回一个binder对象,用户可以使用该binder对象里面的相关接口对service里面的方法进行调用。

首先在创建一个类StudentBinder继承Binder类,然后在onBinder() 方法中奖StudentBinder的实现对象返回,然后供用户调用里面的方法。

具体代码

@Override
public IBinder onBind(Intent arg0) {
      System.out.println("绑定Service");
      return binder;
}
class StudentBinder extends Binder{}


有经验的人,一般是再让StudentBinder继承一个接口,然后在接口中��义方法,然后在StudentBinder内具体实现,然后在Activity直接通过接口调用方法。

下面我们写个接口然后让StudentBinder实现接口。

接口:

public interface IStudent {

       String query(int index);

}

实现:

private String[] strs=new String[]{"刘备","关羽","张飞"};

class StudentBinder extends Binder implements IStudent{

       @Override

       public String query(int index) {

             return strs[index];

       }

}

好,实现写好后,就直接在Activity中利用接口调用。

Activity绑定Service代码:

Intent intent=new Intent(this,StudentService2.class);
bindService(intent, new StudentServiceConnection(), Context.BIND_AUTO_CREATE);
class StudentServiceConnection implements ServiceConnection{
      @Override
      public void onServiceConnected(ComponentName componentName, IBinder binder) {
            service=(IStudent)binder;
      }
      @Override
      public void onServiceDisconnected(ComponentName componectName) {
            service=null;
      }
}


bindService 第二个参数,需要实现ServiceConnection接口,进行与Service连���及断开后的操作。

在连接时,获取binder对象,然后可以调用其内部方法。

btn.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View arg0) {
            text2.setText(service.query(Integer.parseInt(text1.getText().toString())));
      }
});


简单的调用其内部方面,在Activity里显示。

效果

北京联动北方科技有限公司北京联动北方科技有限公司

点击后,调用binder实现方法,返回service数组值。

该贴被java_along编辑于2014-8-3 11:37:44



赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论