如何在计时器任务中停止计时器并在计时器停止后重新启用按钮?

时间:2018-01-31 10:40:40

标签: android sharedpreferences countdowntimer timertask android-broadcastreceiver

我正在尝试使用服务创建一个带有计时器的应用程序,但是计时器工作正常但是我的代码在计时器完成时出现问题(来到0:0)我的按钮应该再次自动重新启用但它保持不变仅在禁用状态下,我尝试了很多重新启用它但没有解决。 所以请看下面的代码并告诉我应该怎么做才能重新启用它? 我是新的服务和Android,任何帮助将不胜感激

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button btn_start;
private TextView tv_timer;
String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
EditText et_hours;

SharedPreferences mpref;
SharedPreferences.Editor mEditor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
    listener();

    et_hours.setVisibility(View.INVISIBLE);

}

private void init() {
    btn_start = (Button) findViewById(R.id.btn_timer);
    tv_timer = (TextView) findViewById(R.id.tv_timer);
    et_hours = (EditText) findViewById(R.id.et_hours);




    mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mEditor = mpref.edit();

    try {
        String str_value = mpref.getString("data", "");
        if (str_value.matches("")) {
            et_hours.setEnabled(false);
            btn_start.setEnabled(true);
            tv_timer.setText("");

        } else {

            if (mpref.getBoolean("finish", false)) {
                et_hours.setEnabled(false);
                btn_start.setEnabled(true);
                tv_timer.setText("");
            } else {

                et_hours.setEnabled(false);
                btn_start.setEnabled(true);
                tv_timer.setText(str_value);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }



}

private void listener() {
    btn_start.setOnClickListener(this);


}

@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.btn_timer:

            et_hours.setText("1");
            et_hours.setEnabled(false);
            btn_start.setEnabled(false);
            calendar = Calendar.getInstance();
            simpleDateFormat = new SimpleDateFormat("mm:ss");
            date_time = simpleDateFormat.format(calendar.getTime());

            mEditor.putString("data", date_time).commit();
            mEditor.putString("hours", et_hours.getText().toString()).commit();


            Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
            startService(intent_service);


            break;

    }

}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String str_time = intent.getStringExtra("time");
        tv_timer.setText(str_time);

    }
};

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(broadcastReceiver,new IntentFilter(Timer_Service.str_receiver));

}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(broadcastReceiver);

}

}

TimerService.java

public class Timer_Service extends Service {

public static String str_receiver = "com.countdowntimerservice.receiver";

private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent;

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

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

    mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mEditor = mpref.edit();
    calendar = Calendar.getInstance();
    simpleDateFormat = new SimpleDateFormat("mm:ss");

    mTimer = new Timer();
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
    intent = new Intent(str_receiver);
}


class TimeDisplayTimerTask extends TimerTask {

    @Override
    public void run() {
        mHandler.post(new Runnable() {

            @Override
            public void run() {

                calendar = Calendar.getInstance();
                simpleDateFormat = new SimpleDateFormat("mm:ss");
                strDate = simpleDateFormat.format(calendar.getTime());
                Log.e("strDate", strDate);
                TimeDifference();


            }

        });
    }

}

public String TimeDifference() {


    try {
        date_current = simpleDateFormat.parse(strDate);
    } catch (Exception e) {

    }

    try {
        date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
    } catch (Exception e) {

    }

    try {


        long diff = date_current.getTime() - date_diff.getTime();
        int int_hours = Integer.valueOf(mpref.getString("hours", ""));

        long int_timer = TimeUnit.MINUTES.toMillis(int_hours);
        long long_hours = int_timer - diff;
        long diffSeconds2 = long_hours / 1000 % 60;
        long diffMinutes2 = long_hours / (60 * 1000) % 60;
        //long diffHours2 = long_hours / (60 * 60 * 1000) % 24;

        if (long_hours >= 0) {
            String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", diffMinutes2, diffSeconds2);
            //String str_testing = diffMinutes2 + ":" + diffSeconds2;

            Log.e("TIME", timeLeftFormatted);

        if (long_hours == 0){
            mEditor.putBoolean("finish", true);
            mTimer.cancel();
        }
            updateTime(timeLeftFormatted);
        } else {
            mEditor.putBoolean("finish", true).commit();
            mTimer.cancel();
        }

    }catch (Exception e){
        mTimer.cancel();
        mTimer.purge();


    }

    return "";

}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("Service finish","Finish");
}

private void updateTime(String str_time){

    intent.putExtra("time",str_time);
    sendBroadcast(intent);
}

}

1 个答案:

答案 0 :(得分:1)

首先,将 Intent 变为像

这样的实例变量
private Button btn_start;
private TextView tv_timer;
.
.
private Intent intent_service;

init()中,您的代码应该如下所示 -

intent_service = new Intent(getApplicationContext(), Timer_Service.class);
.
.

if (mpref.getBoolean("finish", false)) {
     et_hours.setEnabled(false);
     btn_start.setEnabled(true);
     tv_timer.setText("");
} else {

     et_hours.setEnabled(false);
     btn_start.setEnabled(false);  // a change is here
     tv_timer.setText(str_value);
 }

并在 onClick(查看v)内添加此行代码 -

mEditor.putBoolean("finish", false).commit();
.
.
startService(intent_service); // start the service

现在更改 BroadcastReceiver -

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String str_time = intent.getStringExtra("time");
        tv_timer.setText(str_time);

    }
};

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String str_time = intent.getStringExtra("time");
        tv_timer.setText(str_time);
        if (str_time.equals("00:00")) {
            stopService(intent_service); // stop service after work done
            btn_start.setEnabled(true);
        }

    }
};

现在对 Timer_Service 类进行一些小改动 -

if (long_hours == 0){
    mEditor.putBoolean("finish", true).commit(); // a change is here
    mTimer.cancel();
}

尝试一下,让我知道它是否有效。