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

Android Service 基本用法完整梳理:從啟動停止到 IntentService

編輯:關於 Android 程式設計

作為 Android 四大組件之一,Service 的知識點一點都不少,自然也該從最基本的用法開始學起。

定義一個服務

public class MyService extends Service {

    /** onBind 是繼承 Service 後唯一的抽象方法,必須重寫 */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /** 服務每次啟動時呼叫 */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    /** 服務建立時呼叫 */
    @Override
    public void onCreate() {
        Log.i("MyService", "onCreate");
        super.onCreate();
    }

    /** 服務銷毀時呼叫 */
    @Override
    public void onDestroy() {
        Log.i("MyService", "onDestroy");
        super.onDestroy();
    }
}

啟動與停止服務

public class MyServiceActivity extends Activity {

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

        Button start = (Button) findViewById(R.id.start);
        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyServiceActivity.this, MyService.class);
                startService(intent);   // 啟動服務
            }
        });

        Button stop = (Button) findViewById(R.id.stop);
        stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyServiceActivity.this, MyService.class);
                stopService(intent);    // 停止服務
            }
        });
    }
}

注意,上面這段程式碼完全由 Activity 決定服務何時停止;只要不點 Stop Service,服務就會一直運行。那服務能不能自己停下來?當然可以,只要在 MyService 的任一位置呼叫 stopSelf() 即可。

Logcat 的輸出如下:

點擊 start 成功啟動,點擊 stop 成功銷毀。運行成功後可以在「正在運行的應用」清單中找到它,停止之後就消失了:

這裡有個常見疑問:onCreate() 與 onStartCommand() 到底差在哪?因為剛才點 Start Service 時兩者都執行了。答案是:onCreate() 只在服務第一次建立時呼叫,而 onStartCommand() 每次啟動服務都會呼叫。第一次點擊時服務尚未建立,所以兩個都跑;之後連續多按幾次 Start Service,就會發現只有 onStartCommand() 被執行。

Activity 與 Service 通訊

用 startService() 啟動服務後,MyService 的 onCreate() 與 onStartCommand() 會執行,之後服務持續運行,但具體在做什麼、做到哪一步,Activity 一無所知。這就像我們只是通知服務一聲「你可以啟動了!」,然後服務就埋頭忙自己的事。

要讓兩者關係更緊密——例如在 Activity 中指揮服務做事、隨時查看進度——就得用上先前忽略的 onBind()。

舉例來說,若希望在 MyService 裡提供下載功能,由 Activity 決定何時開始、並隨時查詢進度,做法是建立一個專門的 Binder 物件來管理下載:

public class MyService extends Service {

    /** 建立 binder 物件 */
    DownLoadBind bind = new DownLoadBind();

    class DownLoadBind extends Binder {
        /** 開始下載 */
        public void startDownload() {
            Log.i("DownLoadBind", "startDownload");
        }

        /** 取得進度 */
        public int getProgress() {
            Log.i("DownLoadBind", "getProgress");
            return 0;
        }
    }

    /** onBind 是繼承 Service 後唯一的抽象方法,必須重寫。
     *  目的是讓外部能與服務通訊,例如由 Activity 指揮服務做事。
     *  回傳 binder 物件 */
    @Override
    public IBinder onBind(Intent intent) {
        return bind;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        Log.i("MyService", "onCreate");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.i("MyService", "onDestroy");
        super.onDestroy();
    }
}

Activity 這邊則新增兩個按鈕:

public class MyServiceActivity extends Activity {

    private MyService.DownLoadBind down;

    /** 建立 ServiceConnection 匿名內部類並重寫兩個方法 */
    private ServiceConnection connection = new ServiceConnection() {

        /** 與服務解除綁定時呼叫 */
        @Override
        public void onServiceDisconnected(ComponentName name) { }

        /** 綁定成功時呼叫 */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 向下轉型取得 DownLoadBind 實例,此後 Activity 與服務的關係就非常緊密
            down = (MyService.DownLoadBind) service;
            down.startDownload();
            down.getProgress();
        }
    };

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

        Button start = (Button) findViewById(R.id.start);
        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyServiceActivity.this, MyService.class);
                startService(intent);
            }
        });

        Button stop = (Button) findViewById(R.id.stop);
        stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyServiceActivity.this, MyService.class);
                stopService(intent);
            }
        });

        Button bind = (Button) findViewById(R.id.BindService);
        bind.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyServiceActivity.this, MyService.class);
                /* 第一個參數是 Intent,第二個是 ServiceConnection 實例,
                 * 第三個是標誌位。傳入 BIND_AUTO_CREATE 表示綁定後自動建立服務,
                 * 這會讓 onCreate() 執行,但不會執行 onStartCommand()。 */
                bindService(intent, connection, BIND_AUTO_CREATE);
            }
        });

        Button unbind = (Button) findViewById(R.id.UnbindService);
        unbind.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(connection);  // 解綁後服務就會停止運行
            }
        });
    }
}

至此,Activity 可以呼叫服務中任何 public 方法,真正做到「想讓服務做什麼就做什麼」。

值得補充的是,同一個服務在整個應用範圍內都是通用的:MyService 不只可以與 MainActivity 綁定,也可以與任何其他 Activity 綁定,且綁定完成後取得的都是同一個 Binder 實例。

服務的生命週期

如同 Activity 與 Fragment,服務也有自己的生命週期。onCreate()、onStartCommand()、onBind() 與 onDestroy() 都是生命週期內可能回呼的方法。

只要在專案任何位置呼叫 Context 的 startService(),服務就會啟動並回呼 onStartCommand();若此前尚未建立,onCreate() 會先於 onStartCommand() 執行。服務啟動後會持續運行,直到 stopService() 或 stopSelf() 被呼叫。要留意的是,每呼叫一次 startService(),onStartCommand() 就執行一次,但實際上每個服務只存在一個實例——所以不管啟動多少次,只要呼叫一次 stopService() 或 stopSelf(),服務就會停下。

另一條路是呼叫 Context 的 bindService() 取得持久連線,此時會回呼 onBind()(若服務尚未建立,onCreate() 仍會先執行)。呼叫方取得 onBind() 回傳的 IBinder 實例後,就能自由與服務通訊;只要連線未斷,服務便持續運行。

銷毀方面:startService() 之後呼叫 stopService(),onDestroy() 會執行;bindService() 之後呼叫 unbindService(),onDestroy() 同樣會執行。但要注意,我們完全可能對同一個服務既 startService() 又 bindService()。依 Android 的機制,服務只要「被啟動」或「被綁定」其中任一條件成立就會持續運行,必須兩者同時不成立才會銷毀。因此這種情況下要同時呼叫 stopService() 與 unbindService(),onDestroy() 才會觸發。

使用 IntentService

服務中的程式碼預設運行在主線程,若直接處理耗時邏輯,很容易觸發 ANR(Application Not Responding)。標準做法是在每個方法裡另開子線程:

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 處理具體邏輯
                stopSelf();
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }
}

寫法雖不算複雜,但總有人忘了開線程,或忘了呼叫 stopSelf()。為了能簡單地建立「非同步且會自動停止」的服務,Android 提供了 IntentService:

public class MyIntentService extends IntentService {

    /** 必須呼叫父類的有參數建構子 */
    public MyIntentService() {
        super("MyIntentService");
    }

    /** 在這裡處理具體邏輯,不必擔心 ANR,因為本方法已在子線程中運行 */
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("MyIntentService", "子線程ID" + Thread.currentThread().getId());
    }

    /** 服務建立後會自動停止 */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("MyIntentService", "onDestroy");
    }
}

在 Activity 中新增一個按鈕,分別印出子線程與主線程的 ID:

Button startintent = (Button) findViewById(R.id.startintent);
startintent.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.i("MyServiceActivity", "主線程ID" + Thread.currentThread().getId());
        Intent intent = new Intent(MyServiceActivity.this, MyIntentService.class);
        startService(intent);
    }
});

Logcat 輸出:

可以看到,MyIntentService 與 MainActivity 的線程 ID 並不相同,而且 onDestroy() 確實被執行了,說明 MyIntentService 在任務完成後自動停止。「開線程」與「自動停止」兩件事一次搞定,這也是 IntentService 頗受歡迎的原因。

後台執行的定時任務

接著做一個能長期在後台跑定時任務的服務。Android 的定時任務一般有兩種實作方式:Java API 的 Timer 類,以及 Android 的 Alarm 機制。這裡看 Alarm:

public class LongRunningService extends Service {

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("LongRunningService", "executed at " + new Date().toString());
            }
        }).start();

        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int interval = 3000;    // 每隔三秒刷新一次

        /* SystemClock.elapsedRealtime() 取得開機至今的毫秒數;
         * System.currentTimeMillis() 取得 1970-01-01 00:00 至今的毫秒數。 */
        long triggerAtTime = SystemClock.elapsedRealtime() + interval;

        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

        /* set() 的第一個參數用來指定 AlarmManager 的工作類型,共四種:
         * ELAPSED_REALTIME         從開機起算,不喚醒 CPU
         * ELAPSED_REALTIME_WAKEUP  從開機起算,會喚醒 CPU
         * RTC                      從 1970-01-01 起算,不喚醒 CPU
         * RTC_WAKEUP               從 1970-01-01 起算,會喚醒 CPU
         *
         * 第二個參數是觸發時間(毫秒)。若使用 ELAPSED_* 類型,
         * 傳入「開機至今 + 延遲時間」;若使用 RTC 類型,
         * 則傳入「1970 至今 + 延遲時間」。
         *
         * 第三個參數是 PendingIntent,通常呼叫 getBroadcast() 取得可執行廣播的物件,
         * 這樣定時任務觸發時,廣播接收器的 onReceive() 就會被執行。 */
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);

        return super.onStartCommand(intent, flags, startId);
    }
}

Activity 側只要啟動服務:

Button button = (Button) findViewById(R.id.startAlarm);
button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MyServiceActivity.this, LongRunningService.class);
        startService(intent);
    }
});

而 AlarmReceiver 的內容非常簡單:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent2 = new Intent(context, LongRunningService.class);
        context.startService(intent2);
    }
}

關鍵就在這裡:一旦啟動 LongRunningService,就會在 onStartCommand() 中設定定時任務;時間到之後 AlarmReceiver 的 onReceive() 執行,我們在裡頭再次啟動 LongRunningService,於是形成一個永久循環。一個長期在後台定時運行的服務就此完成。

最後別忘了在 AndroidManifest.xml 中註冊。運行後 Logcat 會每隔三秒印出一次時間,實務上把 LOG 換成真正的業務邏輯即可。

綜合範例:通知欄版本升級

最後看一個結合 Service、Handler 多線程、HttpURLConnection 與通知欄的升級下載範例。

public class UpdateService extends Service {

    public static final String Install_Apk = "Install_Apk";

    /** 下載進度的每次遞增值 */
    private static final int down_step_custom = 3;
    private static final int TIMEOUT = 10 * 1000;   // 超時
    private static String down_url;
    private static final int DOWN_OK = 1;
    private static final int DOWN_ERROR = 0;

    private String app_name;
    private NotificationManager notificationManager;
    private Notification notification;
    private PendingIntent pendingIntent;
    private RemoteViews contentView;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        app_name = intent.getStringExtra("Key_App_Name");
        down_url = intent.getStringExtra("Key_Down_Url");

        // 建立檔案;實務上應在此判斷 SD 卡是否就緒、檔案是否建立成功
        FileUtil.createFile(app_name);
        if (FileUtil.isCreateFileSucess == true) {
            createNotification();
            createThread();
        } else {
            Toast.makeText(this, R.string.insert_card, Toast.LENGTH_SHORT).show();
            stopSelf();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /** 更新 UI */
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_OK:
                    // 下載完成,準備安裝
                    Uri uri = Uri.fromFile(FileUtil.updateFile);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    pendingIntent = PendingIntent.getActivity(UpdateService.this, 0, intent, 0);
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.setLatestEventInfo(UpdateService.this, app_name,
                            getString(R.string.down_sucess), pendingIntent);
                    notificationManager.notify(R.layout.notification_item, notification);
                    stopSelf();
                    break;
                case DOWN_ERROR:
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.setLatestEventInfo(UpdateService.this, app_name,
                            getString(R.string.down_fail), null);
                    stopSelf();
                    break;
                default:
                    break;
            }
        }
    };

    private void installApk() {
        Uri uri = Uri.fromFile(FileUtil.updateFile);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 使用 Context 的 startActivity 需要開啟新的 task
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        UpdateService.this.startActivity(intent);
    }

    /** 開啟下載線程 */
    public void createThread() {
        new DownLoadThread().start();
    }

    private class DownLoadThread extends Thread {
        @Override
        public void run() {
            Message message = new Message();
            try {
                long downloadSize = downloadUpdateFile(down_url, FileUtil.updateFile.toString());
                if (downloadSize > 0) {
                    message.what = DOWN_OK;
                    handler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                message.what = DOWN_ERROR;
                handler.sendMessage(message);
            }
        }
    }

    /** 建立通知欄 */
    public void createNotification() {
        notification = new Notification(
                R.drawable.icon,        // 應用圖示
                app_name + getString(R.string.is_downing),
                System.currentTimeMillis());
        notification.flags = Notification.FLAG_ONGOING_EVENT;

        // 自訂通知欄版面
        contentView = new RemoteViews(getPackageName(), R.layout.notification_item);
        contentView.setTextViewText(R.id.notificationTitle, app_name + getString(R.string.is_downing));
        contentView.setTextViewText(R.id.notificationPercent, "0%");
        contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
        notification.contentView = contentView;

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(R.layout.notification_item, notification);
    }

    /** 下載檔案 */
    public long downloadUpdateFile(String down_url, String file) throws Exception {
        int down_step = down_step_custom;
        int totalSize;              // 檔案總大小
        int downloadCount = 0;      // 已下載大小
        int updateCount = 0;        // 已更新到通知欄的百分比
        InputStream inputStream;
        OutputStream outputStream;

        URL url = new URL(down_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(TIMEOUT);
        httpURLConnection.setReadTimeout(TIMEOUT);

        totalSize = httpURLConnection.getContentLength();
        if (httpURLConnection.getResponseCode() == 404) {
            throw new Exception("fail!");
        }

        inputStream = httpURLConnection.getInputStream();
        outputStream = new FileOutputStream(file, false);   // 檔案存在則覆寫

        byte buffer[] = new byte[1024];
        int readsize = 0;
        while ((readsize = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, readsize);
            downloadCount += readsize;

            // 每增加 3% 更新一次通知欄
            if (updateCount == 0 || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
                updateCount += down_step;
                contentView.setTextViewText(R.id.notificationPercent, updateCount + "%");
                contentView.setProgressBar(R.id.notificationProgress, 100, updateCount, false);
                notification.contentView = contentView;
                notificationManager.notify(R.layout.notification_item, notification);
            }
        }

        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        inputStream.close();
        outputStream.close();
        return downloadCount;
    }
}

檔案工具類負責準備存放 APK 的目錄:

public class FileUtil {

    public static File updateDir = null;
    public static File updateFile = null;

    /** 保存升級 APK 的目錄 */
    public static final String KonkaApplication = "konkaUpdateApplication";
    public static boolean isCreateFileSucess;

    public static void createFile(String app_name) {
        if (android.os.Environment.MEDIA_MOUNTED.equals(
                android.os.Environment.getExternalStorageState())) {
            isCreateFileSucess = true;
            updateDir = new File(Environment.getExternalStorageDirectory()
                    + "/" + KonkaApplication + "/");
            updateFile = new File(updateDir + "/" + app_name + ".apk");
            if (!updateDir.exists()) {
                updateDir.mkdirs();
            }
            if (!updateFile.exists()) {
                try {
                    updateFile.createNewFile();
                } catch (IOException e) {
                    isCreateFileSucess = false;
                    e.printStackTrace();
                }
            }
        } else {
            isCreateFileSucess = false;
        }
    }
}

Activity 只需一行觸發:

// 點擊更新
update.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(context, UpdateService.class);
        intent.putExtra("Key_App_Name", appName);
        intent.putExtra("Key_Down_Url", appUrl);
        startService(intent);
        popupWindow.dismiss();
    }
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved