編輯:關於 Android 程式設計
上一篇提到,Service 在背景啟動後不會自動銷毀,結束方式有兩種:外部呼叫 stopService(),或在繼承 Service 的類別中呼叫 stopSelf()。
那什麼時候該呼叫 stopSelf() 呢?如果不呼叫,Service 就會一直掛在背景保持網路連線狀態,電量與資源消耗可想而知。本篇示範如何借助 Handler 的訊息傳遞機制,在下載完成後主動結束 Service。
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 一定要在清單檔案中註冊,否則執行時會直接報錯。
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 把「確定已完成」的訊號送回來再停止,時序才可控。
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" /> 與網路權限,同時涉及背景網路與儲存寫入的應用還需在後續版本中處理執行期權限申請。
Volley + ImageLoader + RecyclerView:打造可下載圖片的瀑布流
要用網絡數據拼出一個能看圖片的瀑布流,關鍵不在演算法,而在幾個成熟框架的搭配是否順手。這篇的目標很明確:從伺服器拉一份 JSON,解析出圖片網址清單,交給 Recycle
安卓實作:子線程與主線程的互動(時鐘範例)
這個範例示範如何在子線程中即時產生時間,並透過 Handler 更新到主線程的介面上。 先看版面配置: 主程式如下。子線程每隔一秒產生一次時間資料,透過 Ha
Android ProgressBar 客製化:旋轉動畫與自訂水平進度條
ProgressBar 是少數「預設樣式很醜、但客製化很簡單」的元件。本文示範兩種常見需求:換掉那個轉圈圈的小動畫,以及做出一條自訂配色的水平進度條。 一、自訂旋轉類型的
Android Loading 界面:以 Shader 實現動態圖片顯示
先看效果圖(方框由左至右依序顯示): 圖片資源: 原理介紹: 第一步:把三張圖片按位置擺放妥當。此時圖片資源會全部顯示,目的是先確保位置的正確性。 第二步:撰寫 sh