一个IntentService使用实例

主线程进度条显示后台耗时任务的执行进度,主线程和后台子线程通过广播机制进行通信。


MainActivity.java文件:

package com.example.edgarperez.intentservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    private ProgressBar progressBar;
    private Button execute;

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

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        execute = (Button) findViewById(R.id.execute);
        execute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent msgIntent = new Intent(getApplicationContext(), ServiceUpdate.class);
                msgIntent.putExtra("duration", 10);
                startService(msgIntent);
            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addAction(ServiceUpdate.ACTION_PROGRESS);
        filter.addAction(ServiceUpdate.ACTION_END);
        MainReceiver receiver = new MainReceiver();
        registerReceiver(receiver, filter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class MainReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ServiceUpdate.ACTION_PROGRESS)){
                int progress = intent.getIntExtra("progress", 0);
                progressBar.setProgress(progress);
            }else if (intent.getAction().equals(ServiceUpdate.ACTION_END)){
                Toast.makeText(MainActivity.this, "Tarea finalizada", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

ServiceUpdate.java文件:

package com.example.edgarperez.intentservice;

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

/**
 * Created by Edgar Perez on 13/06/2015.
 */
public class ServiceUpdate extends IntentService {

    public static final String ACTION_PROGRESS = "com.example.edgarmoises.action.PROGRESS";
    public static final String ACTION_END = "com.example.edgarmoises.intent.action.END";

    public ServiceUpdate() {
        super("ServiceUpdate");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        int duration = intent.getIntExtra("duration", 0);

        for (int i=1; i<=duration; i++){
            Task();

            Intent broadcastProgress = new Intent();
            broadcastProgress.setAction(ACTION_PROGRESS);
            broadcastProgress.putExtra("progress", i * 10);
            sendBroadcast(broadcastProgress);
        }

        Intent broadcastEnd = new Intent();
        broadcastEnd.setAction(ACTION_END);
        sendBroadcast(broadcastEnd);
    }

    private void Task(){
        try {
            Thread.sleep(1000);
        }catch (InterruptedException e){
            Log.e("Task", "Error task: " + e);
        }
    }
}

activity_main.xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"/>

    <Button
        android:id="@+id/execute"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/execute"/>

</LinearLayout>


该实例源码来自:https://github.com/edgarmoises/IntentService

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值