Android中Services之异步IntentService
2016-01-26 17:46
183 查看
IntentService有以下特点:
(1) 它创建了一个独立的工作线程来处理所有的通过onStartCommand()传递给服务的intents。
(2) 创建了一个工作队列,来逐个发送intent给onHandleIntent()。
(3) 不需要主动调用stopSelft()来结束服务。因为,在所有的intent被处理完后,系统会自动关闭服务。
(4) 默认实现的onBind()返回null
(5) 默认实现的onStartCommand()的目的是将intent插入到工作队列中
继承IntentService的类至少要实现两个函数:构造函数和onHandleIntent()函数。要覆盖IntentService的其它函数时,注意要通过super调用父类的对应的函数。
界面设置两按钮:
<Button android:id="@+id/btnStartIntentService" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="开始下载" > </Button> <Button android:id="@+id/btnStopIntentService" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="结束下载" > </Button>
声明IntentServiceSub继承IntentService
public class IntentServiceSub extends IntentService { private static final String TAG = "IntentServiceSub"; public IntentServiceSub() { super("IntentServiceSub"); Log.i(TAG, "=>IntentServiceSub"); } /* (non-Javadoc) * @see android.app.IntentService#onCreate() */ @Override public void onCreate() { Log.i(TAG, "=>onCreate"); super.onCreate(); } /* (non-Javadoc) * @see android.app.IntentService#onDestroy() */ @Override public void onDestroy() { Log.i(TAG, "=>onDestroy"); super.onDestroy(); } @Override protected void onHandleIntent(Intent arg0) { Log.i(TAG, "IntentService 线程:"+Thread.currentThread.getId()); Thread.sleep(2000); }
页面按钮事件
btnStartIntentService = (Button) this.findViewById(R.id.btnStartIntentService); btnStopIntentService = (Button) this.findViewById(R.id.btnStopIntentService); private OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { case R.id.btnStartIntentService: Log.i(TAG, "主线程ID:"+Thread.currentThread.getId()); if (mServiceIntent == null) mServiceIntent = new Intent(AndroidServiceActivity.this,IntentServiceSub.class); startService(mServiceIntent); break; case R.id.btnStopIntentService: Log.i(TAG, "btnStopIntentService"); if (mServiceIntent != null) { stopService(mServiceIntent); mServiceIntent = null; } break; } } };
作者:欢醉
【一个码农的日常】
出处:http://www.cnblogs.com/zhangs1986/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
相关文章推荐
- Android瀑布流照片墙实现,体验不规则排列的美感
- Android ListView异步加载图片错位、重复、闪烁分析以及解决方案
- android 加载器loader详解
- Android分包MultiDex原理详解
- Android开发之ExpandableListView
- Android断点续传的内容
- Android图片虚化源码
- Android入门:Activity四种启动模式
- android反混淆工具
- Android JAVA 裁剪、压缩图片
- Android开发,AchartEngine使用
- Android导入第三方静态库.a编译成动态库.so
- Android Studio使用新的Gradle构建工具配置NDK环境
- android INSTALL_FAILED_CONFLICTING_PROVIDER
- 【Android】读取sdcard卡上的全部图片而且显示,读取的过程有进度条显示
- Android 判断是否是第一次启动
- Android解析xml数据的一种常用方式——PULL解析器解析
- android studio 多版本打包
- Android 利用ViewHolder优化自定义Adapter
- Android Theme中的一些属性