Androi组件Service的子类IntentService

来源:互联网 发布:手机网络ip地址查询 编辑:程序博客网 时间:2024/06/14 04:50

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>
0 0