總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。

2014年7月21日 星期一

[Android] 保持Service開啟 不被移除

API LV14以後提供了新功能,開啟「最近使用的應用程式」拉掉Task,不只是移除shortcut罷了,而是直接停掉該APP(包括期內service)。

API LV 14 以上有個新 override function public void onTaskRemoved( Intent rootIntent ) {}; This is called if the service is currently running and the user has removed a task that comes from the service's application. 







public class Service_RestoreTime extends Service{
     java.text.SimpleDateFormat sdfDateTimeString = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm");
     int i=0;
     final int DEFAULT_HH = 1;
     final int DEFAULT_MM = 59;
     final int DEFAULT_SS = 59;
     int restore_hh;
     int restore_mm;
     int restore_ss;
     static boolean serviceOnStart = false;
     private Context mContext;
     private ContentResolver mResolver;
     private SharedPreferences mPref;
     private String savedParameters;

     @Override
        public void onCreate() {       
        super.onCreate();
        mContext = getApplicationContext();  //系統資料是安全的.
        mResolver = getContentResolver();  //在這裡也可以存取database.
        mPref = getSharedPreferences("Prefs", 0);  //建議在onDestroy裡面實作儲存parameter的動作,並在這裡回復。
       
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(mReceiver, filter);    //broadcast receiver 也安全。       
        }

    private Handler handler = new Handler();

    @Override
        public void onStart(Intent intent, int startId) {
        int now_hh = mPref.getInt("HH", DEFAULT_HH);
        int now_mm = mPref.getInt("MM", DEFAULT_MM);
        int now_ss = mPref.getInt("SS", DEFAULT_SS);
        if((now_hh == 0) && (now_mm == 0) && (now_ss == 0)){
            restore_hh=DEFAULT_HH;
            restore_mm=DEFAULT_MM;
            restore_ss=DEFAULT_SS;           
        }else{
            restore_hh = now_hh;
            restore_mm = now_mm;
            restore_ss = now_ss;
        }       
        handler.postDelayed(showTime, 1000);//每隔一秒啟動一次
        super.onStart(intent, startId);
        }

      // 當service被移除時, 將值存入SharedPreferences
        @Override
        public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Editor editor = mPref.edit();
        editor.putInt("HH", restore_hh);
        editor.putInt("MM", restore_mm);
        editor.putInt("SS", restore_ss);       
        editor.commit();
        }

    // 被系統low memory killed 並重啓的時候, intent為null
    public int onStartCommand(Intent intent, int flags, int startId) {
            super.onStartCommand(intent, flags, startId);
            return START_STICKY;  //回傳此值才能讓系統幫你在資源允許的時候自動回復service。
        }

        private Runnable showTime = new Runnable() {
            public void run() {           
                String time = String.valueOf(restore_hh)+":"+String.valueOf(restore_mm)+":"+String.valueOf(restore_ss);
                if(MainActivity.time != null){
                    MainActivity.time.setText(getString(R.string.tv_hint_restoretime, time));
                }
               
                if((restore_hh == 0) && (restore_mm == 0) && (restore_ss == 0)){
                    commitPref();
                    if(MainActivity.time != null){
                        MainActivity.time.setText(String.valueOf(MainActivity.PLAYTIMESDAILY));
                    }                 
                      serviceOnStart = false;
                      handler.removeCallbacks(showTime);
                      return;//會讓這個function迴圈停止
                }else{
                 count();
                    restore_ss--;               
                }
                serviceOnStart = true;
                handler.postDelayed(this, 1000);//一定要放最後面, 否則在後面的code會執行不到
            }
        };

    public void count() {
                if(restore_ss == 0){
                    restore_mm--;
                    restore_ss = DEFAULT_SS+1;
                    if(restore_mm == -1){
                        restore_ss = DEFAULT_SS+1;
                        restore_mm = DEFAULT_MM;
                        restore_hh--;
                        if(restore_hh == -1){
                            restore_ss = DEFAULT_SS+1;
                            restore_mm = DEFAULT_MM;                  
                        }               
                    }
                }  
    }
}

============================Log===============================  
 07-21 18:02:04.420: D/522(1703): -[1][Service_RestoreTime][onTaskRemoved]user手動移除service 
07-21 18:02:04.500: D/522(1703): -[1][Service_RestoreTime][commitPref]存入hh = 1 
07-21 18:02:04.510: D/522(1703): -[1][Service_RestoreTime][commitPref]存入mm = 42 
07-21 18:02:04.515: D/522(1703): -[1][Service_RestoreTime][commitPref]存入ss = 34 
07-21 18:02:29.815: D/522(4356): -[1][Service_RestoreTime][onStartCommand] 07-21 18:02:29.830: D/522(4356): -[1][Service_RestoreTime][onStart]取出hh = 1 07-21 18:02:29.830: D/522(4356): -[1][Service_RestoreTime][onStart]取出mm = 42 
07-21 18:02:29.830: D/522(4356): -[1][Service_RestoreTime][onStart]取出ss = 34 07-21 18:02:29.835: D/522(4356): -[1][Service_RestoreTime][onStart]接續server, 1:42:34
==============================================================  

Activity啟動service:
Intent intent = new Intent(context, Service_RestoreTime.class); startService(intent);  

Activity關閉service:
Intent intent = new Intent(tabActivity.this, Service_RestoreTime.class); stopService(intent);

沒有留言:

張貼留言