Service的理解和用法

Servic是可以在後臺運行的服務,一個程序只會有一個服務的實例。

startService(),stopService()的用法和startActivity()一樣。

後臺執行指定的服務代碼:

package com.example.administrator.app1;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;


public class MyService extends Service {
public MyService() {
}

private  Boolean serviceRunning = false;//判斷service是否開始執行

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
//在startService執行之後,都會執行到onStartCommand
public int onStartCommand(Intent intent, int flags, int startId) {

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

@Override
//oncreate只會執行一次,服務只有一個實例
public void onCreate() {
    super.onCreate();
    serviceRunning = true;
    new Thread(){
        @Override
        public void run() {
            super.run();
            while(serviceRunning) {//循環執行程序
                System.out.println("程序正在運行。。。");

                try {
                    sleep(1000);//休眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

@Override
public void onDestroy() {
    super.onDestroy();
    serviceRunning = false;
}

}

activity和service進行綁定的時候也會執行oncreate和onstartcommand

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章