Android中Services之异步IntentService

IntentService:异步处理服务,新开一个线程:handlerThread在线程中发消息,然后接受处理完成后,会清理线程,并且关掉服务。

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;
            }

        }
    };
复制代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值