首页 > 代码库 > android命令模式IntentService 远程下载文件

android命令模式IntentService 远程下载文件

服务可用在一下情景:
1,用户离开activity后,仍需要继续工作,例如从网络下载文件,播放音乐.
2,无论activity出现或离开,都需要持续工作,例如网络聊天应用.
3,连接网络服务,正在使用一个远程API提供的服务.
4,定时触发的任务

1.因为IntentService是Service子类,所以也需要在manifest中声明服务

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.intentservicedemo"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.example.intentservicedemo.ServiceDownloader"></service>
    </application>
</manifest>

2,新建 ServiceDownloader 继承自 IntentService

public class ServiceDownloader extends IntentService {
       //避免出现命名重复,将类的命名空间加在前面
    public static final String EXTRA_MESSAGER="com.wei.android.learning.ServiceDownloader.EXTRA_MESSAGER";
    public ServiceDownloader() {
        super("ServiceDownloader");
    }
    //命令模式的服务由client请求服务,
    private HttpClient client=null;
    int result ;
    private Intent mIntent;
    
    //client通过startService请求服务时,如果没有开启,则会首先执行onCreate(),在这里做一些初始化的工作,onCreate是在主线程中运行
    @Override
    public void onCreate() {
        super.onCreate();
        client=new DefaultHttpClient();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
        
    }
    //再收到客户端命令,处理完onStartCommand()后执行,onHandleIntent()是在后台线程中运行
    @Override
    protected void onHandleIntent(Intent i) {
        this.mIntent=i;
        result = Activity.RESULT_CANCELED
        HttpGet get=new HttpGet(i.getData().toString());
        ResponseHandler<byte[]> responseHandler =new ByteArrayResponseHandler();
        try {
            byte[] responseByte=client.execute(get,responseHandler);
            File output=new File(Environment.getExternalStorageDirectory(),i.getData().getLastPathSegment());
            if(output.exists()){
                output.delete();
            }
            FileOutputStream fos=new FileOutputStream(output.getPath());
            fos.write(responseByte);
            fos.close();
            result=Activity.RESULT_OK;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bundle extras=i.getExtras();
        if(extras!=null){
            Messenger messenger =(Messenger) extras.get(EXTRA_MESSAGER);
            Message msg=Message.obtain();
            msg.arg1=result;
            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public void onDestroy() {
        Bundle extras=mIntent.getExtras();
        if(extras!=null){
            Messenger messenger =(Messenger) extras.get(EXTRA_MESSAGER);
            Message msg=Message.obtain();
            msg.arg1=result;
            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        client.getConnectionManager().shutdown();
        super.onDestroy();
    }
    
    private class ByteArrayResponseHandler implements ResponseHandler<byte[]>{
        @Override
        public byte[] handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            StatusLine statusLine=response.getStatusLine();
            if(statusLine.getStatusCode()>300){
                throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase()); 
            }
            HttpEntity entity=response.getEntity();
            if(entity==null){
                return null;
            }
            return EntityUtils.toByteArray(entity);
        }
    }
}

3,在客户端调用服务,开启下载任务,并且在下载完成时,可以收到下载完成的消息
public class MainActivity extends ActionBarActivity {
    
    Button btn_start;
    Button btn_stop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_start=(Button) findViewById(R.id.btn_start);
        btn_stop=(Button) findViewById(R.id.btn_stop);
        btn_start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startDownLoader();
            }
        });
        btn_stop.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                stopDownLoader();
            }
        });
    }
    
    private void startDownLoader(){
        Intent intent=new Intent(this, ServiceDownloader.class);
        intent.setData(Uri.parse("http://commonsware.com/Android/excerpt.pdf")); 
        intent.putExtra(ServiceDownloader.EXTRA_MESSAGER,new Messenger(mh));
        startService(intent);
    }
    
    private Handler mh=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //下载完成后,将取消服务按钮失效
            switch (msg.arg1) {
            case Activity.RESULT_OK:
                Toast.makeText(MainActivity.this"Result : OK " , Toast.LENGTH_LONG).show();
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(MainActivity.this"Result : Cancel " , Toast.LENGTH_LONG).show();
                break;
            default:
                break;
            }
        }
    };
    private void stopDownLoader(){
        stopService(new Intent(this, ServiceDownloader.class));
    }
    
}

4,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:orientation="vertical"
    tools:context="com.example.intentservicedemo.MainActivity" >
    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="start"
        android:id="@+id/btn_start"
        />
    <Button 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="stop"
        android:id="@+id/btn_stop"
        />
</LinearLayout>




来自为知笔记(Wiz)


android命令模式IntentService 远程下载文件