无法在Android中停止计时器?怎么解决?

时间:2017-04-28 05:48:31

标签: android timer countdowntimer

我正在编写一个类来控制Android中的启动和停止计时器。控制器是一个将发送开始或结束值的活动。在TimerControl类中,我编写了两个用于启动和停止计时器的函数。我可以启动计时器,但我无法阻止它。我该如何解决?这是我的代码

//In Controller class
//===========Start========
 Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
 smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 smsTimer.putExtra("input_timer", "start");
 getApplicationContext().startActivity(smsTimer);
 //===========Stop========
 Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
 smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 smsTimer.putExtra("input_timer", "stop");
 getApplicationContext().startActivity(smsTimer);

这是我的TimerControl代码

public class TimmerControl extends Activity {
    private CountDownTimer timer_SMS;
    private String TAG="TimmerControl";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent != null &&intent.getExtras() != null) {
            Bundle bundle = intent.getExtras();
            if (!bundle.getString("input_timer").equals(null)) {
                String  input_timer = bundle.getString("input_timer");                
                if(input_timer.equals("start")) {// start
                        startSMSTimer();
                }
                else if(input_timer.equals("stop")) {// stop
                    stopSMSTimer();
                }
                else{}
            }
        }
        finish();
    }
    public void startSMSTimer(){
        if (timer_SMS != null) {
            timer_SMS.cancel();
            timer_SMS = null;
        }
        timer_SMS = new CountDownTimer(100000, 20000) {
            @Override
            public void onTick(long millisUntilFinished) {               
                    long timOver = 100000 - millisUntilFinished;
                    Log.d(TAG, String.valueOf(timOver));      
            }

            @Override
            public void onFinish() { }
        };
        timer_SMS.start();
    }
    public void stopSMSTimer(){
        if (timer_SMS != null) {
            timer_SMS.cancel();
            timer_SMS = null;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

你需要发送"停止"发送停止意图如下:

//In Controller class
//===========Start========
 Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
 smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 smsTimer.putExtra("input_timer", "start"); // start
 getApplicationContext().startActivity(smsTimer);
 //===========Stop========
 Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
 smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 smsTimer.putExtra("input_timer", "stop"); // stop 
 getApplicationContext().startActivity(smsTimer);

答案 1 :(得分:1)

public class TimmerControl extends Service {

    CountDownTimer timer_SMS;
    private BroadcastReceiver mReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("start");
        intentFilter.addAction("stop");

        mReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                //extract our message from intent

                if (intent.getAction().equals("start")) {
                    startSMSTimer();
                }
                if (intent.getAction().equals("stop")) {
                    stopSMSTimer();
                }

            }
        };

        this.registerReceiver(mReceiver, intentFilter);
    }


    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(this.mReceiver);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void startSMSTimer() {
        if (timer_SMS != null) {
            timer_SMS.cancel();
            timer_SMS = null;
        }
        timer_SMS = new CountDownTimer(100000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long timOver = 100000 - millisUntilFinished;

                Log.e("Time: ", ""+timOver);
            }

            @Override
            public void onFinish() {
                Log.e("finished: ","");
            }
        };
        timer_SMS.start();
    }

    public void stopSMSTimer() {
        if (timer_SMS != null) {
            timer_SMS.cancel();
            timer_SMS = null;
            Log.e("Stop: ","");
        }
        stopSelf();
    }

}        


    SMSControllerActivity.java


    public class SMSControllerActivity extends AppCompatActivity {

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

        findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isServiceRunning(TimmerControl.class))
                    startService(new Intent(SMSControllerActivity.this, TimmerControl.class));
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sendBroadcast(new Intent("start"));
                    }
                }, 500);

            }
        });
        findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendBroadcast(new Intent("stop"));
            }
        });
        ;
    }

    private boolean isServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    }


    activity_smscontroller.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn_start"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="Start" />

        <Button
            android:id="@+id/btn_stop"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="Stop" />

    </LinearLayout>