activity 与service 互相传值

本文介绍在Android开发中如何实现Activity与Service之间的数据传递,包括从Activity向Service发送数据的方法,以及Service如何通过广播向Activity传递消息。

activity中 向service传值

与ativity互相传值类似

在activity中

Intent regIntent = new Intent(this, ChatService.class);
  regIntent.putExtra("student_id",student_id);
  startService(regIntent);

然后再service中的onStart函数中获取该值

student_id=intent.getStringExtra("student_id");
  System.out.println("sevice_student_id---------------"+student_id);

当然写到这里还是不能传的,不然会报错!!!

我们需要在Mainfeist文件中注册这个service

销毁Service写在activity的onDestroy方法里:

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

补充:

也可以从public int onStartCommand(Intent intent, int flags, intstartId)中取出从activity中传过来的值。intent.getExtra()获得bundle对象,可从中取值。
也可以用bindService(intent,conn,BIND_AUTO_CREATE);传值,把要传的值绑定在intent里,在service的public IBinderonBind(Intent intent) 方法里取得intent。
可以在service里面注册一个广播,在activity里sendbroadcast(intent)传值。



Service要给Activity传递消息,需要用到广播。


这里,使用的是前两个例子的代码,只是在Service每隔2秒就自动发送一个广播。而activity在收到广播后,更新一个textview的显示。


Service的代码:


    private void doInBackground() {  
            new Thread(new Runnable() {  
                public void run() {  
                    for (int i = 0; i < 10; i++) {  
                        Intent intent = new Intent("com.gdp2852.demo.service.broadcast");  
                        intent.putExtra("i", ""+i);  
                        sendBroadcast(intent);  
                        try {  
                            Thread.sleep(2000);  
                        } catch (InterruptedException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                }  
            }).start();  
        }  


Receiver的代码:

    IntentFilter filter = new IntentFilter("com.gdp2852.demo.service.broadcast");  
            registerReceiver(receiver, filter);  


     private BroadcastReceiver receiver = new BroadcastReceiver() {  
        public void onReceive(Context context, Intent intent) {  
            TextView tv = (TextView) findViewById(R.id.tv);  
            tv.setText("发送过来的内容:"+intent.getExtras().getString("i"));  
            Toast.makeText(Demo_ServiceActivity.this, intent.getAction()+" i:"+intent.getExtras().getString("i"), Toast.LENGTH_LONG).show();              
        }  
    };  


相关工程文件请下载:

http://download.csdn.net/detail/gdp2852/3792795


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值