以Service來紀錄各種state,
在 Android 有四種 application components:
1. Activities
2. Services
3. Content providers
4. Intent
在 Android 應用程式裡,有一種沒有 UI 的類別(android.app.Service),稱之為 Service。
Service (import android.app.Service) 是一個 background process(背景程序),不像 Activity 有著介面可以讓使用者操作, Service 的生命周期都是比較長,可以在背景長駐執行一些不中斷的程式, 像是背景錄音, 播放音樂, 定期自動更新
PersonRecordService.java
public class PersonRecordService extends Service{ static final int IDLE_STATE = 0; static final int RECORDING_STATE = 1; static final int PLAYING_STATE = 2; static final int PAUSE_STATE = 3; int mState = 0; public interface OnStateChangedListener { public void onStateChanged(int state); public void onError(int error); } OnStateChangedListener mOnStateChangedListener = null; public void setOnStateChangedListener(OnStateChangedListener listener) { mOnStateChangedListener = listener; } private void setState(int state) { mState = state; signalStateChanged(mState); } private void signalStateChanged(int state) { if (mOnStateChangedListener != null) mOnStateChangedListener.onStateChanged(state); } }
PersonRecordActivity.java
public class PersonRecordActivity extends Activity implements PersonRecordService.OnStateChangedListener { PersonRecordService personRecordService = new PersonRecordService(); personRecordService.setOnStateChangedListener(this); WakeLock mWakeLock; public void onCreate(Bundle savedInstanceState) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "PersonRecord"); @Override public void onStateChanged(int state) { if (state == PersonRecordService.PLAYING_STATE || state == PersonRecordService.RECORDING_STATE) { // 背景恆亮 mWakeLock.acquire(); } else { if (mWakeLock.isHeld()) // 取消背景恆亮 mWakeLock.release(); } updateUi(); } @Override public void onError(int error) { } } }
當手機在螢幕醒著的狀態, 長時間不觸碰面板則螢幕會自動暗掉, 進而進入待機狀態,
為防止手機進入待機狀態, 則需使用到 PowerManage 這個功能
AndroidManifest.xml
沒有留言:
張貼留言