- static的參考不見的時候該怎麼辦
- 傳進來的intent是null的時候該怎麼辦
- service被系統kill掉之後該怎麼辦
下面的範例程式碼來說明。
public class ChachaService extends Service { private Context mContext; private ContentResolver mResolver; private SharedPreferences mPref; private String savedParameters; public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mContext = getApplicationContext(); //系統資料是安全的. mResolver = getContentResolver(); //系統資料是安全的. 所以在這裡也可以存取database. mPref = getSharedPreferences("Prefs", 0); //安全. 建議在onDestroy裡面實作儲存parameter的動作,並在這裡回復。 savedParameters = mPref.getString("savedparameter", "aaaa"); IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); registerReceiver(mReceiver, filter); //broadcast receiver 也安全。 } public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub super.onStartCommand(intent, flags, startId); //注意! 被系統low memory killed 並重啓的時候, intent為null! //! boolean bool = intent.getBooleanExtra("xxxx", false); return START_STICKY; //回傳此值才能讓系統幫你在資源允許的時候自動回復service。 } private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ... } public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mReceiver != null) unregisterReceiver(mReceiver); Editor editor = mPref.edit(); editor.putString("savedparameter", savedParameters); editor.commit(); } }
0 件のコメント:
コメントを投稿