用Android-Studio的IntentService模板快速实现业务需求(实战)

一、用Android-Studio开发工具,新建一个IntentService。
用Android-Studio的IntentService模板快速实现业务需求(实战)_第1张图片
二、勾选“开始方法助手”,其实就是IntentService的模板写法。
用Android-Studio的IntentService模板快速实现业务需求(实战)_第2张图片
三、详细看下模板内容。
package com.czz.manager.service;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * 

* TODO: Customize class - update intent actions, extra parameters and static * helper methods. */ public class MyIntentService extends IntentService { // TODO: Rename actions, choose action names that describe tasks that this // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS private static final String ACTION_FOO = "com.czz.manager.service.action.FOO"; private static final String ACTION_BAZ = "com.czz.manager.service.action.BAZ"; // TODO: Rename parameters private static final String EXTRA_PARAM1 = "com.czz.manager.service.extra.PARAM1"; private static final String EXTRA_PARAM2 = "com.czz.manager.service.extra.PARAM2"; public MyIntentService() { super("MyIntentService"); } /** * Starts this service to perform action Foo with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method public static void startActionFoo(Context context, String param1, String param2) { Intent intent = new Intent(context, MyIntentService.class); intent.setAction(ACTION_FOO); intent.putExtra(EXTRA_PARAM1, param1); intent.putExtra(EXTRA_PARAM2, param2); context.startService(intent); } /** * Starts this service to perform action Baz with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method public static void startActionBaz(Context context, String param1, String param2) { Intent intent = new Intent(context, MyIntentService.class); intent.setAction(ACTION_BAZ); intent.putExtra(EXTRA_PARAM1, param1); intent.putExtra(EXTRA_PARAM2, param2); context.startService(intent); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_FOO.equals(action)) { final String param1 = intent.getStringExtra(EXTRA_PARAM1); final String param2 = intent.getStringExtra(EXTRA_PARAM2); handleActionFoo(param1, param2); } else if (ACTION_BAZ.equals(action)) { final String param1 = intent.getStringExtra(EXTRA_PARAM1); final String param2 = intent.getStringExtra(EXTRA_PARAM2); handleActionBaz(param1, param2); } } } /** * Handle action Foo in the provided background thread with the provided * parameters. */ private void handleActionFoo(String param1, String param2) { // TODO: Handle action Foo throw new UnsupportedOperationException("Not yet implemented"); } /** * Handle action Baz in the provided background thread with the provided * parameters. */ private void handleActionBaz(String param1, String param2) { // TODO: Handle action Baz throw new UnsupportedOperationException("Not yet implemented"); } }

第一:四个私有的、静态的和最终的常量。两个用来Action标识,两个用来参数标识。
题外话:为什么用 ACTION_FOO ACTION_BAZ 来标识两个动作。FOO与BRZ的含义是什么?
答案的 网址:https://en.wikipedia.org/wiki/Foobar ;
第二:有 startActionFoo startActionBaz ,来分别启动不同的Service。
          启动 Service的 时候,顺便传参 EXTRA_PARAM1 EXTRA_PARAM2
第三:核心就是 onHandleIntent ,方法 intent 不为null,同时取得的匹配则调用相应的方法 handleActionFoo handleActionBaz

四、实战IntentService。
业务需求:在 Service里开启次线程请求网络数据,将返回的数据通过广播( Broadcast )传给活动(Activity),更新UI视图。
IntentService+Thread+Broadcast+Activity。
根据官方提供的模板,填写自己的类。
(1)自定义IntentService类:
package com.czz.manager.service;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import com.czz.manager.bean.NewsInfo;
import com.czz.manager.bean.WeatherInfo;
import java.util.ArrayList;

public class TestIntentService extends IntentService {

    //TODO :①定义ACTION常量,action_news和action_weather,即“新闻”和“天气”
    private static final String ACTION_NEWS = "com.czz.manager.service.action.NEWS";
    private static final String ACTION_WEATHER = "com.czz.manager.service.action.WEATHER";

    //TODO :②启动Service,需要传一些参数
    private static final String EXTRA_PARAM1 = "com.czz.manager.service.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.czz.manager.service.extra.PARAM2";

    //TODO :③获得结果之后需要用Broadcast将结果发送给Activity以更新UI视图
    private static final String NEWS_RESULT = "com.czz.manager.service.RESULT.NEWS";
    private static final String WEATHER_RESULT = "com.czz.manager.service.RESULT.WEATHER";
    //TODO :④发送广播,需要传入的一些参数
    private static final String EXTRA_PARAM3 = "com.czz.manager.service.extra.PARAM3";
    private static final String EXTRA_PARAM4 = "com.czz.manager.service.extra.PARAM4";

    public TestIntentService() {
        super("TestIntentService");
    }
    public static void startActionNEWS(Context context, String param1, String param2) {
        Intent intent = new Intent(context, TestIntentService.class);
        intent.setAction(ACTION_NEWS);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    public static void startActionWEATHER(Context context, String param1, String param2) {
        Intent intent = new Intent(context, TestIntentService.class);
        intent.setAction(ACTION_WEATHER);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_NEWS.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionNEWS(param1, param2);
            } else if (ACTION_WEATHER.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionWEATHER(param1, param2);
            }
        }
    }

    private void handleActionNEWS(String param1, String param2) {

        //次线程里操作网络请求数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList arrayList = getNews();
                Intent intent = new Intent(NEWS_RESULT);
                // 此处传送的数据的是集合类型,也可以有其他的类型:intent.put
                intent.putParcelableArrayListExtra(EXTRA_PARAM3, arrayList);
                sendBroadcast(intent);
            }
        }).start();
    }

    private void handleActionWEATHER(String param1, String param2) {
        //次线程里操作网络请求数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList arrayList = getWeather();
                Intent intent = new Intent(WEATHER_RESULT);
                // 此处传送的数据的是集合类型
                intent.putParcelableArrayListExtra(EXTRA_PARAM4, arrayList);
                sendBroadcast(intent);
            }
        }).start();
    }

    private ArrayList getWeather() {
        ArrayList list=null;
        // 从网络上的JSON数据转为集合,可以是[retrofit2]框架异步操作
        // ...
        return list;
    }

    private ArrayList getNews() {
        ArrayList list=null;
        // 从网络上的JSON数据转为集合
        // ...
        return list;
    }
}

(2)Activity:
package com.czz.manager.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.czz.manager.R;
import com.czz.manager.bean.NewsInfo;
import com.czz.manager.bean.WeatherInfo;

import java.util.ArrayList;

public class TestActivity extends AppCompatActivity {

    //TODO :③获得结果之后需要用Broadcast将结果发送给Activity以更新UI视图
    private static final String NEWS_RESULT = "com.czz.manager.service.RESULT.NEWS";
    private static final String WEATHER_RESULT = "com.czz.manager.service.RESULT.WEATHER";
    //TODO :④发送广播,需要传入的一些参数
    private static final String EXTRA_PARAM3 = "com.czz.manager.service.extra.PARAM3";
    private static final String EXTRA_PARAM4 = "com.czz.manager.service.extra.PARAM4";

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

        //注册广播,以接收Service通过广播发送过来的数据
        registerReceiver();
        //启动服务
        TestIntentService.startActionNEWS(this, null, null);
        TestIntentService.startActionWEATHER(this, null, null);
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        //区分多种广播
        filter.addAction(NEWS_RESULT);
        filter.addAction(WEATHER_RESULT);
        registerReceiver(receiver, filter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(NEWS_RESULT)) {
                Log.i("mylog", "NEWS广播接收器中...");
                ArrayList arrayList = intent.getParcelableArrayListExtra(EXTRA_PARAM3);
                //获取到了数据,进行一些UI更新...
            } else if (intent.getAction().equals(WEATHER_RESULT)) {
                Log.i("mylog", "WEATHER广播接收器中...");
                ArrayList arrayList = intent.getParcelableArrayListExtra(EXTRA_PARAM4);
                //获取到了数据,进行一些UI更新...
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

(3)JavaBean:
此处给出NewsInfo类,Weather类省略。需要实现Parcelable接口
package com.czz.manager.bean;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by XiuChou on 2016/8/19
 */

public class NewsInfo implements Parcelable {

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeString(article_url);
        out.writeString(behot_time);
        out.writeInt(bury_count);
        out.writeInt(digg_count);
        out.writeInt(repin_count);
        out.writeInt(create_time);
        out.writeInt(publish_time);
        out.writeString(source);
        out.writeString(title);
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public NewsInfo createFromParcel(Parcel in) {
            return new NewsInfo(in);
        }

        public NewsInfo[] newArray(int size) {
            return new NewsInfo[size];
        }
    };

    private NewsInfo(Parcel in) {
        article_url = in.readString();
        behot_time = in.readString();
        bury_count = in.readInt();
        digg_count = in.readInt();
        repin_count = in.readInt();
        create_time = in.readInt();

        publish_time = in.readInt();

        source = in.readString();
        title = in.readString();

    }

    private String article_url;//Http,Url
    private String behot_time;//时间

    private int bury_count;//踩数
    private int digg_count;//点赞数
    private int repin_count;//收藏数

    private int create_time;//创建时间

    private String group_id;
    private int publish_time;//发布时间

    private String source;//来源
    private String title;//新闻标题

    public int getCreate_time() {
        return create_time;
    }

    public int getDigg_count() {
        return digg_count;
    }

    public String getGroup_id() {
        return group_id;
    }

    public int getPublish_time() {
        return publish_time;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public int getRepin_count() {
        return repin_count;
    }

    public void setRepin_count(int repin_count) {
        this.repin_count = repin_count;
    }

    public void setPublish_time(int publish_time) {
        this.publish_time = publish_time;
    }

    public void setGroup_id(String group_id) {
        this.group_id = group_id;
    }

    public void setDigg_count(int digg_count) {
        this.digg_count = digg_count;
    }

    public void setCreate_time(int create_time) {
        this.create_time = create_time;
    }

    public int getBury_count() {
        return bury_count;
    }

    public void setBury_count(int bury_count) {
        this.bury_count = bury_count;
    }

    public String getArticle_url() {
        return article_url;
    }

    public void setArticle_url(String article_url) {
        this.article_url = article_url;
    }

    public String getBehot_time() {
        return behot_time;
    }

    public void setBehot_time(String behot_time) {
        this.behot_time = behot_time;
    }

    @Override
    public String toString() {
        return "NewsInfo{" +
                "article_url='" + article_url + '\'' +
                ", behot_time='" + behot_time + '\'' +
                ", bury_count=" + bury_count +
                ", digg_count=" + digg_count +
                ", repin_count=" + repin_count +
                ", create_time=" + create_time +
                ", group_id='" + group_id + '\'' +
                ", publish_time=" + publish_time +
                ", source='" + source + '\'' +
                ", title='" + title + '\'' +
                '}';
    }
}
实现效果图:
用Android-Studio的IntentService模板快速实现业务需求(实战)_第3张图片
新闻接口: http://api.1-blog.com/biz/bizserver/news/list.do ;

博主认为还需改进的地方就是启动服务的方法在Service里设置则需要设置为static的,这样在Activity中要启动Service则需要[类名].[方法名],耦合姓太高。
建议讲启动Service的方法定义在Activity中。

 
 

你可能感兴趣的:(Android)