Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 應用:利用 Service 生命週期在背景下載圖片(原始碼分享)

編輯:關於 Android 程式設計

上一篇提到,Service 在背景啟動後不會自動銷毀,結束方式有兩種:外部呼叫 stopService(),或在繼承 Service 的類別中呼叫 stopSelf()。

那什麼時候該呼叫 stopSelf() 呢?如果不呼叫,Service 就會一直掛在背景保持網路連線狀態,電量與資源消耗可想而知。本篇示範如何借助 Handler 的訊息傳遞機制,在下載完成後主動結束 Service。

MainActivity

package com.example.f21_service01;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button button;

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

        button = (Button) this.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DownLoadService.class);
                startService(intent);   // 透過 Intent 啟動 Service
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Activity 這邊很單純,按鈕觸發啟動 Service。要再次強調:Service 一定要在清單檔案中註冊,否則執行時會直接報錯。

DownLoadService

package com.example.f21_service01;

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class DownLoadService extends Service {
    private static final String path = "https://my.csdn.net/u013900875";

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                stopSelf();   // 收到訊息後關閉 Service
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new MyThread()).start();   // 啟動下載執行緒
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public class MyThread implements Runnable {
        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(path);
            try {
                HttpResponse httpResponse = client.execute(httpPost);
                byte[] result = EntityUtils.toByteArray(httpResponse.getEntity());
                // 寫入記憶卡成功後將旗標設為 true
                boolean flag = SDcardtoFile.WriteToFile("hello", result);
                if (flag) {
                    handler.sendEmptyMessage(1);   // 透過 Handler 發送訊息
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

流程是這樣:在 onStartCommand() 啟動下載執行緒,下載完成並成功寫入記憶卡後把 flag 設為 true,透過 Handler 的 sendEmptyMessage() 發訊號,主執行緒收到後呼叫 stopSelf()。

為什麼不直接在下載執行緒裡呼叫 stopSelf()?因為這個方法的停止時機是不確定的,後續程式碼仍可能繼續執行。透過 Handler 把「確定已完成」的訊號送回來再停止,時序才可控。

SDcardtoFile 寫入工具

package com.example.f21_service01;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Environment;

public class SDcardtoFile {
    public static boolean WriteToFile(String name, byte[] data) {
        boolean flag = false;
        String state = Environment.getExternalStorageState();
        FileOutputStream fileOutputStream = null;

        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(Environment.getExternalStorageDirectory(), name);
            try {
                fileOutputStream = new FileOutputStream(file);
                try {
                    fileOutputStream.write(data, 0, data.length);
                    flag = true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return flag;
    }
}

寫檔前先用 Environment.getExternalStorageState() 確認外部儲存空間已掛載,是必須的防禦性寫法;否則在沒有 SD 卡的裝置上會直接拋出 FileNotFoundException。另外別忘了在清單中加入 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 與網路權限,同時涉及背景網路與儲存寫入的應用還需在後續版本中處理執行期權限申請。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved