Android如何在运行时更改倒数计时器值

时间:2015-08-05 06:55:07

标签: android

我在后台服务中运行倒数计时器。我的服务从我的MainActivity开始,如给出的

startService(new Intent(this, BroadcastService.class));

在我的BroadcastService oncreate()中,我正在调用倒数计时器,并从用户设置的sharedpref中计算它的倒计时时间。我的问题是用户可以改变倒数计时器时间。当用户设置倒数计时器时间我将我的活动切换到MainActivity,所以服务应该再次呼叫,倒数计时器应该为它设置新的值。但是在Calling MainActivity倒数计时器没有为新时间设置它的值。我做错了什么。

BroadCastService

public class BroadcastService extends Service {

    private final static String TAG = "BroadcastService";
    DataManager dm_obj;
    private NotificationManager mManager;
    String check_time_format,check_current_time;
    long difference;
    public static final String COUNTDOWN_BR = "com.example.wajibati.countdown_br";
    Intent bi = new Intent(COUNTDOWN_BR);
    boolean check_daylight_saving;
    CountDownTimer cdt = null;
    int time_format;
    int alarm_type;
    boolean isIshaFinished;
    @Override
    public void onCreate() {       
        super.onCreate();

        dm_obj=new DataManager(getApplicationContext());
        isIshaFinished=false;
        Log.i(TAG, "Starting timer...");
        time_format=dm_obj.loadTimeFormat();
        check_daylight_saving=dm_obj.loadDaylight();
        if(time_format==0){
            check_time_format="hh:mm aa";

        }else{

            check_time_format="kk:mm";
        }
        CalculateTimedifference();
        RunCountDownTimer();


    }


## MainActivity ##

    public class MainActivity extends Activity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_main);
       startService(new Intent(this, BroadcastService.class));
      }

       private BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {            
            updateGUI(intent); // or whatever method used to update your GUI fields
        }
    };
    @Override  
    public void onResume() {
        super.onResume();        
        registerReceiver(br, new   IntentFilter(BroadcastService.COUNTDOWN_BR));

    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(br);

    }

    @Override
    public void onStop() {
        try {
            unregisterReceiver(br);
        } catch (Exception e) {
            // Receiver was probably already stopped in onPause()
        }
        super.onStop();
    }
    @Override
    public void onDestroy() {        
        stopService(new Intent(this, BroadcastService.class));

        super.onDestroy();
    }

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为当第二次BroadcastService已经在运行时你可以从MainActivity启动Service()时,所以不会调用服务的OnCreate()方法来调用你的倒计时器。

您可能应该将代码从onCreate()替换为服务中的onStartCommand()。