Widget与service利用BroadcastReceiver通信

  Widget与service通信一直是个难点,在网上发现一位仁兄的方法不错,特来分享:

  AppWidgetProvider中要注册intent主要是为了处理点击事件,或者是更新widgets中的数据,接受来自应用中数据的改变消息。

  通常我们会创建一个Service,在Service中注册,处理intent.下面的注册,接收时间改变的消息

  public class WidgetService extends Service{

  private WidgetsProvider mAppWidgetProvider = WidgetsProvider .getInstance();//widgets事例

  private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {//广播消息的处理

  @Override

  public void onReceive(Context context, Intent intent) {

  if(Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())||Intent.ACTION_TIME_TICK.equals(intent.getAction())||Intent.ACTION_TIME_CHANGED.equals(intent.getAction()))

  {

  notifyChange(Intent.ACTION_TIMEZONE_CHANGED);

  }

  }

  };

  @Override

  public void onCreate() {

  super.onCreate();

  //消息的注册

  IntentFilter commandFilter = new IntentFilter();

  commandFilter.addAction(Intent.ACTION_TIME_TICK);

  commandFilter.addAction(Intent.ACTION_TIME_CHANGED);

  commandFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);

  getBaseContext().registerReceiver(mIntentReceiver, commandFilter);

  }

  @Override

  public void onDestroy() {

  //注销

  unregisterReceiver(mIntentReceiver);

  super.onDestroy();

  }

  lcbjzl2.cn.zhongsou.net

  wzbjzw3.cn.zhongsou.net

  labjzl4.cn.zhongsou.net

  czbjzc8.cn.zhongsou.net

  lfbjzl3.cn.zhongsou.net

  whbjzw6.cn.zhongsou.net

  qdbjzq3.cn.zhongsou.net

  ycbjzy5.cn.zhongsou.net

  ylbjzy1.cn.zhongsou.net

  csbjzc1.cn.zhongsou.net

  hebbjz4.cn.zhongsou.net

  ncbjzn4.cn.zhongsou.net

  ykbjzy1.cn.zhongsou.net

  xybjzx4.cn.zhongsou.net

  xmbjzx2.cn.zhongsou.net

  fzbjzf4.cn.zhongsou.net

  wzbjzw4.cn.zhongsou.net

  sxbjzs1.cn.zhongsou.net

  hzbjzh6.cn.zhongsou.net

  jnbjzj3.cn.zhongsou.net

  dybjzd4.cn.zhongsou.net

  hfbjzh4.cn.zhongsou.net

  labjzz.cn.zhongsou.net

  czbjzc9.cn.zhongsou.net

  czbjzc10.cn.zhongsou.net

  zzbjzz9.cn.zhongsou.net

  jcbjzj4.cn.zhongsou.net

  nbbjzn6.cn.zhongsou.net

  nbbjzn7.cn.zhongsou.net

  wzbjzb.cn.zhongsou.net

  sxbjzs2.cn.zhongsou.net

  hzbjzz1.cn.zhongsou.net

  jhbjzj1.cn.zhongsou.net

  jnbjzj4.cn.zhongsou.net

  lybjzz.cn.zhongsou.net

  qdbjzt.cn.zhongsou.net

  whbjzw7.cn.zhongsou.net

  dybjzd5.cn.zhongsou.net

  ytbjzy2.cn.zhongsou.net

  wfbjzw1.cn.zhongsou.net

  hzbjzh7.cn.zhongsou.net

  @Override

  public IBinder onBind(Intent intent) {

  return null;

  }

  private void notifyChange(String what) {

  mAppWidgetProvider.notifyChange(this, what);//widgets中消息的处理

  }

  @Override

  public void onStart(Intent intent, int startId) {

  }

  }

  由于service是要通过事件来启动,我们通常是在点击事件中来启动它,如何你在widgets中想程序启动就启动service你需要这样做:

  Intent mrunningService = new Intent(context, WorldClockWidgetService.class);

  // To prevent any ANR timeouts, we perform the update in a service

  context.startService(mrunningService);

你可能感兴趣的:(Widget与service利用BroadcastReceiver通信)