Android——推斷Service是否已經啟動

來源:互聯網
上載者:User

標籤:start   沒有   地圖   pre   _id   work   log   action   running   

          延續百度地圖定位的Demo。採用Service來進行百度定位,並且將資料上傳到server上遇到了一個問題:在真機中使用清理記憶體來關閉程式的之後,Service會被關閉,可是過幾秒中,它又會自己主動重新啟動。重新啟動就算了,並且再次登陸系統的時候,又會開啟一個一樣的服務,在LogCat中就會看到每次都擷取到兩次的定位元據。

然後想想能否夠在建立Service之前推斷這個服務有沒有被建立?僅僅要能做這個推斷。那麼服務存在我們就無論它,假設不存在則建立。本著這個思路,百度發現可行(Service後台服務建立時最好都要推斷是否存在),代碼例如以下:


private boolean isWorked(String className) {ActivityManager myManager = (ActivityManager) LoginActivity.this.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);for (int i = 0; i < runningService.size(); i++) {if (runningService.get(i).service.getClassName().toString().equals(className)) {return true;}}return false;}

推斷過程:

if(!this.isWorked("包.服務名")){Intent intent = new Intent();intent.setAction("該服務元件的intent-filter的action");// 啟動ServicestartService(intent);}else{Log.i("info", "服務已經啟動了!

");}






Android——推斷Service是否已經啟動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.