Androi组件Service的子类IntentService

IntentService:
* 1.内部有一个工作线程来完成耗时的操作,只需要实现handleIntent()即可。
* 2.完成工作后会自动的停止该服务
* 3.如果同时多次的使用该服务执行任务时,会以工作队列的方法,依次的执行。
* 4.使用该类来完成本APP中的耗时工作。

代码如下:

package com.feicui.servicetest.services;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;


public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");//设置工作线程的名字。
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        for (int i=1;i<50;i++){
            Log.i("Text2",i+"------"+Thread.currentThread().getName());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

功能页面代码:

package com.feicui.servicetest;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.feicui.servicetest.services.MyBoundService;
import com.feicui.servicetest.services.MyIntentService;
import com.feicui.servicetest.services.MyService;

public class MainActivity extends AppCompatActivity {


    boolean isBind = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**启动一个IntentService*/
    public void startIntentService(View view){
        Intent intent = new Intent(this, MyIntentService.class);
        startService(intent);
    }

XML代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.feicui.servicetest.MainActivity">

    <Button
        android:text="启动一个IntentService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startIntentService"
        android:id="@+id/button3"
        android:layout_marginTop="37dp"
        android:layout_below="@+id/button2"
        android:layout_alignParentStart="true"
        />
</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值