每次活动恢复时都会重新创建服务

时间:2015-07-25 01:54:39

标签: android service

我在这里遇到了一个非常困难的困境,因为我有一项活动启动了一个运行倒数计时器的服务。每次恢复活动时,服务都会启动另一个倒数计时器。我查找了服务,它有在整个服务中调用一次的方法,并被称为onCreate。唯一的问题是我通过onStartCommand期间检索的意图从活动中接收时间值。在OnStartCommand之前调用onCreate意味着我无法检索这些值并将它们插入onCreate。有没有办法可以将onStartCommand中的值放到onCreate上。以下代码显示了我的问题。

isInProgress()

启动服务

TextView timeTextView;
int data;


public  String hms;
public CountDownAct countDownAct;
public CountDownTime countDownTimer;

@Override
public IBinder onBind(Intent intent) {
    return null;

}

@Override
public void onCreate() {
    super.onCreate();

     //I need the CountDownTimer to start here in order to prevent a new countdown timer from being created each time the activity is resumed.`             
    countDownTimer = new CountDownTime(data,1000 );
    countDownTimer.start();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  //the time data is being retrieved here
  data = intent.getIntExtra("the", 0);

    return START_STICKY;


}

@Override
public boolean stopService(Intent name) {

    Log.i("CountDownService", "Stop Service");
    return super.stopService(name);

}

@Override
public void onDestroy() {

    countDownTimer.cancel();

} 

1 个答案:

答案 0 :(得分:1)

您可以使用SharedPreference来存储actualTimeFiniliazedInMilliSeconds。这可以从服务类中重新获得:

useService = new Intent(CountDownAct.this, CountDownService.class);

SharedPreference mShared = getApplicationContext().getSharedPreference("myShared",Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mShared.edit();
mEditor.putInt("data",actualTimeFiniliazedInMilliSeconds).commit();

startService(useService);

Retriving:

SharedPreference mShared = getApplicationContext().getSharedPreference("myShared",Context.MODE_PRIVATE);
countDownTimer = new CountDownTime(mShared.getInt("data",0),1000);
countDownTimer.start();