关闭

Android~Service+BroadcastReceiver使用

标签: androidservicebroadcastreceiver
1805人阅读 评论(0) 收藏 举报
分类:

由于项目需要,我们有时候需要在service中处理耗时操作,然后将结果发送给activity以更新状态。通常情况下,只需要在一个service与一个activity之间通信,这种情况下,我们使用最多的是通过回调接口。具体做法是在service中定义一个接口,在activity中实现改接口,并通过bindservice来传入。当需要将service中的结果一次发送给多个activity时,我们又该如何实现呢?经过检索,存在三种实现的方式,分别是回调接口、广播接收者和观察者模式 。
本文主要讲解比较推荐的方式——广播接收者。通过广播接收者 ,在service中执行完耗时操作后,将结果以广播的形式发送,在所有的activity中注册广播,接收到结果后更新UI,这种方式比较简单。因为耗时的操作结果不需要以handler的方式发送到主线程,可以直接在子线程中发送广播,接收者始终运行在主线程中。

  • Service.java
package com.example.servicecallback;

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

public class ContentService extends Service {


  @Override
  public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return new LocalBinder();
  }

  @Override
  public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
  }

  public final class LocalBinder extends Binder {
    public ContentService getService() {
      return ContentService.this;
    }
  }

  public void asyncSendPerson(final String name) {
    // 休息5秒,模拟异步任务
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        //可以在子线程中直接发送广播
        sendContentBroadcast(name);
      }
    }).start();
  }

  /**
   * 发送广播
   * @param name
   */
  protected void sendContentBroadcast(String name) {
    // TODO Auto-generated method stub
    Intent intent=new Intent();
    intent.setAction("com.example.servicecallback.content");
    intent.putExtra("name", name);
    sendBroadcast(intent);
  }
}
  • MainActivity.java
package com.example.servicecallback;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends Activity {

  private MyServiceConn conn;
  private TextView mContent;
  private ContentReceiver mReceiver;

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

    conn = new MyServiceConn();
    bindService(new Intent(this, ContentService.class), conn,
        BIND_AUTO_CREATE);

    mContent = (TextView) findViewById(R.id.content);

    this.findViewById(R.id.button1).setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            // TODO Auto-generated method stub
            startActivity(new Intent(MainActivity.this,
                OtherActivity.class));
          }
        });


    doRegisterReceiver();
  }

  /**
   * 注册广播接收者
   */
  private void doRegisterReceiver() {
    mReceiver=new ContentReceiver();
    IntentFilter filter = new IntentFilter(
        "com.example.servicecallback.content");
    registerReceiver(mReceiver, filter);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  public class MyServiceConn implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
      // service = ((LocalBinder) binder).getService();
    }

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

  @Override
  protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    unbindService(conn);
    if (mReceiver!=null) {
      unregisterReceiver(mReceiver);
    }
  }

  public class ContentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      String name = intent.getStringExtra("name");
      Person person = new Person();
      person.setName(name);
      mContent.setText(person.toString());
    }
  }
}
  • OtherActivity.java
package com.example.servicecallback;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.servicecallback.ContentService.LocalBinder;

public class OtherActivity extends Activity {

  private ContentService service;
  private TextView mContent;
  private Button mSubmit;
  private EditText mEditText;
  private ServiceConnection conn;
  private ContentReceiver mReceiver;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.other);

    mEditText = (EditText) findViewById(R.id.edittext);
    mSubmit = (Button) findViewById(R.id.button1);
    mContent = (TextView) findViewById(R.id.content);

    mSubmit.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        String name = mEditText.getText().toString();
        service.asyncSendPerson(name);
      }
    });


    conn=new MyServiceConn();
    bindService(new Intent(OtherActivity.this, ContentService.class), conn,
        BIND_AUTO_CREATE);

    doRegisterReceiver();
  }

  private void doRegisterReceiver() {
    mReceiver=new ContentReceiver();
    IntentFilter filter = new IntentFilter(
        "com.example.servicecallback.content");
    registerReceiver(mReceiver, filter);
  }

  public final class MyServiceConn implements ServiceConnection {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
      service = ((LocalBinder) binder).getService();
    }

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

  @Override
  protected void onDestroy() {
    super.onDestroy();
    unbindService(conn);
    if (mReceiver!=null) {
      unregisterReceiver(mReceiver);
    }
  }

  public class ContentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      String name = intent.getStringExtra("name");
      Person person = new Person();
      person.setName(name);
      mContent.setText(person.toString());
    }
  }
}

  1. http://www.tuicool.com/articles/6bamAjj
  2. http://blog.csdn.net/xiaanming/article/details/9750689
  3. http://blog.csdn.net/pi9nc/article/details/18764415
  4. http://blog.chinaunix.net/uid-20771867-id-164794.html
  5. http://blog.chinaunix.net/uid-20771867-id-166069.html
2
0
查看评论
发表评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场

Android基于BroadcastReceiver和Service、SoundPool开发的防过充助手app

前段时间换了一个小米4C手机,可是发现它的充电充满没有提醒,上一个手机换了就是因为不爱惜电池,让它过充的次数多了,虽然听别人说小米4c手机充电器是智能充电器,有保护作用,但我自己还是不放心,于是就亲手...
  • leonjack123
  • leonjack123
  • 2016-03-11 11:55
  • 520

Android Service 服务(二)—— BroadcastReceiver

一、 BroadcastReceiver简介BroadcastReceiver,用于异步接收广播Intent,广播Intent是通过调用Context.sendBroadcast()发送、Broadc...
  • sunboy_2050
  • sunboy_2050
  • 2012-03-17 21:36
  • 32000

Service结合BroadcastReceiver实现跨进程通信的例子

在Android中跨进程通信是能够经常遇见的 ,像下载大文件需要更新下载进度这种东西,因为我们设置了下载的Service是在独立的进程里边,也就是说不是在默认的UI线程里边,传统的handler就无法...
  • qq_28963915
  • qq_28963915
  • 2016-08-18 17:30
  • 1529

本示例 利用Broadcast Receiver 启动Service

  • 2012-03-18 15:59
  • 24KB
  • 下载

BroadcastReceiver与Service小结

BroadcastReceiver:对象的生命周期不超过5s,如果进行耗时工作,通过开线程,可以通过发送Intent给Activity或Service,由  Activity或者Service来完成。...
  • nmgchfzhzhg
  • nmgchfzhzhg
  • 2010-07-28 11:20
  • 4165

Service结合BroadcastReceiver实现跨进程通信的例子

在Android中跨进程通信是能够经常遇见的 ,像下载大文件需要更新下载进度这种东西,因为我们设置了下载的Service是在独立的进程里边,也就是说不是在默认的UI线程里边,传统的handler就无法...
  • qq_28963915
  • qq_28963915
  • 2016-08-18 17:30
  • 1529

如何在 BroadcastReceiver 中执行耗时操作?

一、BroadcastReceiver 注册方式     BroadcastReceiver 有两种注册方式,一是使用 { Context.registerReceiver()} 动态注册,另一种是...
  • coralline_xss
  • coralline_xss
  • 2017-04-14 13:08
  • 1540

Android应用是否可以只有一个Service或Broadcast Reciver,而没有Activity?

文章来源:http://blog.csdn.net/pku_android/article/details/7329080 Service是android四大组件中与Activity最相似的组件,都...
  • libaineu2004
  • libaineu2004
  • 2015-09-25 17:37
  • 2523

ANDROID---当网络发生变化时使用BroadcastReceiver和service通知

  • 2016-05-30 12:00
  • 23.03MB
  • 下载

ANDROID-当网络发生变化时使用BroadcastReceiver和service通知

  • 2016-05-30 11:46
  • 2.68MB
  • 下载
    最新评论
    个人资料
    • 访问:75757次
    • 积分:1063
    • 等级:
    • 排名:千里之外
    • 原创:51篇
    • 转载:6篇
    • 译文:1篇
    • 评论:9条