《第一行代码》第二版 学习总结31 IntentService服务基本使用

      最近利用下班时间,找了看什么书比较适合初学android的朋友,很多人推荐了这本书,于是就买了一本,感觉看书,思考,动手,再思考和总结这样过程还是很有必要的,于是就打算把自己学习的东西简单的总结一下;方便自己以后查找,也有利于学习的巩固。在这里首先要感谢一下书籍的作者——郭霖前辈。

      前一篇说了关于如何保证服务一直在后台运行(前台服务),那么几天就来说一说如何让服务再完成任务后自动关闭——IntentService。

1,引出缘由

      服务的执行默认是在主线程中执行的,但是有的服务执行的动作往往是很耗时的,也就是说需要手动开一个子线程,此外,像这种很耗时的操作往往又是个比较长的一段时间才需要执行一次,所以如果服务一直这样开着但是又不工作,比较浪费系统资源;所以,我们还需要在服务执行完任务的时候关闭服务。所以这里面就有两点需要时刻注意:

(1)开线程

(2)关服务

      正因为有这样的需要,Android官方也就提供了这样的API——IntentService(其实我们在AS中创建服务的时候,都会有两个选择Service或者IntentService)

使用步骤如下:

第一步:定义服务,继承IntentService,

第二步:添加构造函数,重写onHandleIntent()方法---------需要服务实现的功能

第三步:重写onDestroy()方法---------关闭服务前执行的动作

2,示例代码

MainActivity.java代码:

package com.hfut.operationonintentservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void startNormalService(View view){
        Intent intent=new Intent(this,MyService.class);
        startService(intent);
    }

    public void startIntentService(View view){
       Intent intent=new Intent(this,MyIntentService.class);
       startService(intent);
    }
}
 

MyService.java代码:

package com.hfut.operationonintentservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void startNormalService(View view){
        Intent intent=new Intent(this,MyService.class);
        startService(intent);
    }

    public void startIntentService(View view){
       Intent intent=new Intent(this,MyIntentService.class);
       startService(intent);
    }
}

MyIntentService.java代码:

 

package com.hfut.operationonintentservice;

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

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {
    private static final String TAG = "MyIntentService";
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyIntentService(String name) {
        super(name);
    }

    public MyIntentService() {
       super("MyIntentService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        //执行今天业务,执行完毕,就会执行onDestroy()方法
        Log.i(TAG, "onHandleIntent: 我的业务逻辑是在 "+Thread.currentThread().getName()+" 中完成");
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: IntentService停止");
        super.onDestroy();
    }
}

activity_main.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.hfut.operationonintentservice.MainActivity">

 <Button
     android:layout_marginTop="30dp"
     android:textSize="15dp"
     android:onClick="startNormalService"
     android:text="开启Service服务"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" />

    <Button
        android:layout_marginTop="10dp"
        android:textSize="15dp"
        android:onClick="startIntentService"
        android:text="开启IntentService服务"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

主配置文件AndroidManifest.xml代码:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hfut.operationonintentservice">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyIntentService"
            android:exported="false" />
        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

3,运行结果

第一步:运行程序

                           

第二步:点击“开启SERVICE服务”

第三步:点击“开启SERVICEINTENT服务”

 

总结:在onHandleIntent()中的代码执行是在子线程而非主线程中的,是区别于Service中的onStartCommand()方法的;由此可见,IntentService是一个异步的,可以自动关闭的服务。

(附:今天早上(27号)想一想,还是把IntentService中的代码调整了一下,这样更形象一些,所以调整MyIntentService代码如下:

MyIntentService代码:

package com.hfut.operationonintentservice;

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

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {
    private static final String TAG = "MyIntentService";
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyIntentService(String name) {
        super(name);
    }

    public MyIntentService() {
       super("MyIntentService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        //执行具体业务,执行完毕,就会执行onDestroy()方法

        long timeStart=System.currentTimeMillis();
        long timeEnd=timeStart;
        Log.i(TAG, "onHandleIntent: 我的业务逻辑是在 "+Thread.currentThread().getName()+" 中完成");
        URL url=null;
        HttpURLConnection connection;
        try {
            url=new URL("https://www.baidu.com");
            connection= (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if(connection.getResponseCode()==200){
                timeEnd=System.currentTimeMillis();
                Log.i(TAG, "onHandleIntent: 任务完成,执行耗时"+(timeEnd-timeStart));
            }
            else{
                timeEnd=System.currentTimeMillis();
                Log.i(TAG, "onHandleIntent: 任务异常,执行耗时"+(timeEnd-timeStart));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: IntentService停止");
        super.onDestroy();
    }
}

结果如下:

注:欢迎扫码关注

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值