该活动结束后如何取消预定的通话?

时间:2017-09-19 14:22:26

标签: java android

我在3秒后安排了一个电话,如果该活动关闭(用户移动到另一个活动),我想取消它。
这是我的java文件:

public class EmargencyResponseActivity extends AppCompatActivity {


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


    if (ActivityCompat.checkSelfPermission(EmargencyResponseActivity.this,
            Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(EmargencyResponseActivity.this,new String[]{Manifest.permission.CALL_PHONE},1);


    }
    new CountDownTimer(3000, 1000) {
        public void onFinish() {
            Intent startEmergency = new Intent(Intent.ACTION_CALL, Uri.parse("tel:108"));
            startActivity(startEmergency);
                finish();
            }

        public void onTick(long millisUntilFinished) {
        }
    }.start();}}

1 个答案:

答案 0 :(得分:0)

您可以在活动中保留对计时器的引用,并在onPause

期间取消它
public class EmargencyResponseActivity extends AppCompatActivity {

CountDownTimer timer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //...

    }
    timer = new CountDownTimer(3000, 1000) {
        //Implementation
    }
}

@Override
protected void onPause(){
    if (timer != null) timer.cancel();
}

}