Service学习(六)——在服务与活动间通信

来源:互联网 发布:淘宝图片大小分辨率 编辑:程序博客网 时间:2024/06/08 18:52

Service学习——在服务与活动之间通信

具体做法就是让服务在后台运行周期事件或者长时间事件,然后在特定的时间下或者触发点发送广播,让监听该广播的所有活动做出相应的反应。

先一个简单的:

MyIntentService类:

在此我只贴出需要更改的地方,其他代码同前几篇

protected voidonHandleIntent(Intent arg0) {

                   //TODO Auto-generated method stub

                   try{

                            intresult = DownloadFile(new URL("http://www.baidu.com"));

                            Log.d("IntentService","Downloaded" + result + "bytes");

                           

                            //发送一个广播通知活动,文件已经被下载

                            IntentbroadcastIntent = new Intent();

                            broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");

                            getBaseContext().sendBroadcast(broadcastIntent);

                   }catch (Exception e) {

                            e.printStackTrace();

                   }

         }

MainActivity中的改变:

这些代码写在onCreat中

//用来筛选文件下载的意图

                   intentFilter= new IntentFilter();

                   intentFilter.addAction("FILE_DOWNLOADED_ACTION");

                  

                   //注册接收者

                   MainActivity.this.registerReceiver(intentReceiver,intentFilter);

 

这个写在onCreat外

privateBroadcastReceiver intentReceiver = new BroadcastReceiver() {

                  

                   @Override

                   publicvoid onReceive(Context context, Intent intent) {

                            //TODO Auto-generated method stub

                            Log.d("onReceive","监听到了");

                            Toast.makeText(MainActivity.this,"File downloaded", Toast.LENGTH_LONG).show();

                   }

         };

 

最后在onDestory中注销监听

protected voidonDestroy() {

                   super.onDestroy();

                   unregisterReceiver(intentReceiver);

         };

 

以上就实现了服务与活动的通信功能,你运行程序后会看到大概4秒钟后,出现File Downloaded!在LogCat中看到Downloaded 100bytes

0 0
原创粉丝点击