【Android(安卓)开发教程】在Activity和Service之间建立链接
16lz
2021-01-26
本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。
原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/通常,service总是在它自己的线程里面执行任务,和调用它的activity线程是相互独立的。如果service只是在后台执行一些循环任务,并且不关心service的状态,是不会产生问题的。举个例子,有一个service在后台打印当前设备的地理位置信息。这种情况下,service不需要和任何activity进行交互。因为,service的主要任务就是打印日志。
然而,想像一下,你想要监视一个特定的地理位置,当设备靠近这个地理位置的时候,service打印地址信息,这时,就需要和activity就行交互。下面的例子展示如果实现service和activity之间的交互。
1. 使用Services工程,修改MyIntentService.java文件。
public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentServiceName"); } @Override protected void onHandleIntent(Intent intent) { try { int result = DownloadFile(new URL("http://www.amazon.com/somefile.pdf")); Log.d("IntentService", "Downloaded " + result + " bytes"); //---send a broadcast to inform the activity // that the file has been downloaded--- Intent broadcastIntent = new Intent(); broadcastIntent.setAction("FILE_DOWNLOADED_ACTION"); getBaseContext().sendBroadcast(broadcastIntent); } catch (MalformedURLException e) { e.printStackTrace(); } } private int DownloadFile(URL url) { try { //---simulate taking some time to download a file--- Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 100; }}
2. 修改ServicesActivity.java文件。
public class ServicesActivity extends Activity { IntentFilter intentFilter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public void onResume() { super.onResume(); //---intent to filter for file downloaded intent--- intentFilter = new IntentFilter(); intentFilter.addAction("FILE_DOWNLOADED_ACTION"); //---register the receiver--- registerReceiver(intentReceiver, intentFilter); } @Override public void onPause() { super.onPause(); //---unregister the receiver--- unregisterReceiver(intentReceiver); } public void startService(View view) { startService(new Intent(getBaseContext(), MyIntentService.class)); } public void stopService(View view) { stopService(new Intent(getBaseContext(), MyService.class)); } private BroadcastReceiver intentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(getBaseContext(), "File downloaded!", Toast.LENGTH_LONG).show(); } };}
3. 在模拟器上面调试。
4. 点击start service按钮,大概5秒后会弹出toast提示。
例子很简单,使用广播机制进行线程间的通信。
更多相关文章
- Android(安卓)Handler 用法解析
- PhoneGap API中文帮助文档——Geolocation(地理位置)
- android基础知识02——线程安全2:handler、message、runnable
- Android:如何跟踪第一个Activity界面绘制完成前的时间开销状况及
- Android(安卓)ANR:Application Not Responding
- Java、Android的异常处理原理&Android(安卓)Crash捕获、分发及处
- 百度 腾讯 阿里UC 迅雷 部分Android笔试 面试题
- AsyncTask源码深入分析和巧记线程池
- 深入理解Binder通信原理及面试问题