發表文章

目前顯示的是有「android」標籤的文章

android 背景執行方法 IntentService、Service

圖片
此方法建議不要長期使用timer長期執行,因為手機螢幕關閉後呈待機狀態timer會停止運作,用sleep(1000)也是會停止計時,想做長期定時通知請看我做定時通知 那篇 。 IntentService是Service的簡易版,已內建一個thread,如果只是想用一個thread就好這個非常適合,建立IntentService比建立Service簡單。 IntentService、Service我做的實驗目前情況: IntentService在完全關閉activity後會停止(就是關掉手機佔存在背景activity) Service在完全關閉activity後也會停止,但是能透過重新啟動service的方式重新啟動,可是service的程式就要重新執行一遍。 service 的生命週期 建立class方式 在manifest.xml裡會有 <service android:name=".MyService" android:enabled="true" android:exported="true" /> 在activity啟動service方式 //open intentservice Intent intent = new Intent(this, NotificationService.class); Log.d(TAG, "service start"); startService(intent); Service public class MyService extends Service { public MyService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } @...

android 定時通知(永久長期的) 本篇只講AlarmManager使用

圖片
本篇使用AlarmManager達到準時執行某程式,跟鬧鐘的方式一樣,我之前用過IntentService、Service、Handler,都不能長期使用。 Servicer簡單缺點整理: IntentService:只要關閉activity背景保存視窗,IntentService背景所執行的程式就被強迫結束,好像可以重開(我沒試過)。 Service、Handler:雖然關閉activity會繼續執行,但他是重新在開啟一次service,這到還好,但當手機螢幕關閉處於待機狀態時,service會停止運作暫停在那邊,等你喚醒再繼續執行,所以用這個加timer做定時通知會整個亂掉,timer會停下來不數了。 AlarmManager主要架構是 跟系統註冊鬧鐘甚麼時間點 → 時間到系統會發送一個鬧鈴 → 你的activity接收那個鬧鈴後執行你的程式 當你註冊好幾個鬧鐘已經晚於現在時間,他會馬上通通都執行完 先建立接收鬧鈴的程式 在Manifest.xml 中加入接收系統鬧鈴 <application> <activity android:name=".MainActivity"> </activity> <!-- 當鬧鈴時間到達時要執行的程式 --> <receiver android:name=".AlarmReceiver"> <intent-filter> <action android:name="activity_app" /> </intent-filter> </receiver> </application> 建立一個class檔,執行接收到鬧鈴後的程式 public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ...

android 手機螢幕翻轉 Activity 介面不更新

雖然用WebView可以顯示網頁,但是當手機翻轉後,他會重新再載入一次網頁,每翻轉一次就重新loading,使用者不舒服,service也會多負擔。 在 AndroidManifest.xml 加入 <manifest> <application> <activity ... android:name=".MainActivity" ... android:configchanges="orientation|keyboardhidden|screensize"> ↑ 加入這行 ↑ <intent-filter> <action android:name="android.intent.action.MAIN"/> </intent-filter> </activity > ... </application> </manifest> 從 Android 3.2 (API 13) 開始,螢幕翻轉螢幕尺寸也會跟著改變,所以要再加上 screenSize 在 Activity 中加入 @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { // 什麼都不用寫 } else { // 什麼都不用寫 } } 參考自: 官方: https://developer.androi...