如何在后台运行倒数计时器

时间:2016-04-18 05:25:13

标签: android timer

我正在做一个需要倒数计时器来限制时间为1小时的项目。 我已对此进行了编码,但每次刷新活动时,倒数计时器都会从开始时开始。 我该怎么办。

这是我的代码

new CountDownTimer(3600000, 1000) {
                     @Override
                     public void onTick(long millisUntilFinished) {
                         long millis = millisUntilFinished;
                         mTimer.setText("" + String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                                 TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                                 TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
                     }
                     @Override
                     public void onFinish() {
                         mTimer.setText("");
                         unlock();
                         mStatus.setTextColor(Color.parseColor("#f9d540"));
                     }
                 }.start();

谢谢:)

这些是我的活动代码。我试过在AsyncTask中做这件事(只是//等待)

String ipParse;
long CountTimer;
TextView mName,mUsername,mLicense,mLot,mStatus, mDate, mPayment, mTel,mTimer,mconfirm;
ImageView imageView,Ask;
Button unlock, layout, logout;
private String login_name, user_license, lot_lot;
private IPManager ipManager;
private LoginManager loginManager;
AlertDialog alertDialog;

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

    loginManager = new LoginManager(this);
    ipManager = new IPManager(this);
    ipParse = ipManager.Read_ip();


    login_name = getIntent().getStringExtra("username");
    user_license = getIntent().getStringExtra("license");
    lot_lot = getIntent().getStringExtra("lot");


    mName     = (TextView) findViewById(R.id.name);
    mUsername = (TextView) findViewById(R.id.user_username);
    mLicense  = (TextView) findViewById(R.id.license_user);
    mLot      = (TextView) findViewById(R.id.yourlot);
    mStatus   = (TextView) findViewById(R.id.status_parking);
    mDate     = (TextView) findViewById(R.id.date);
    mPayment  = (TextView) findViewById(R.id.payment);
    mTel      = (TextView) findViewById(R.id.tel);
    mTimer    = (TextView) findViewById(R.id.Timer);
    mconfirm  = (TextView) findViewById(R.id.confirmation);

    imageView = (ImageView) findViewById(R.id.pic_parking);
    Ask       = (ImageView) findViewById(R.id.pic_Ask);

    unlock = (Button) findViewById(R.id.button_unlock);
    layout = (Button) findViewById(R.id.layout_building);
    logout = (Button) findViewById(R.id.log_out);

    unlock.setVisibility(View.GONE);



    PostFunction postM =new PostFunction();

    //Check Status
    try {
        String resp = postM.postCheck2a(ipParse, user_license, lot_lot);
        JSONObject object = new JSONObject();
        try {
            object = new JSONObject(resp);
            int status = object.getInt("status");
            int status_2a = object.getInt("status_2a");



            //waiting
             if (status == 0 && status_2a == 1){

                 unlock.setVisibility(View.VISIBLE);


                 Ask.setVisibility(View.GONE);

                mconfirm.setText("time for confirmation");
                 mStatus.setTextColor(Color.parseColor("#20b2aa"));


                 new UpdateCountdownTask().execute();



            }

            //wrong lot!!!!
            else if (status == 0 && status_2a == 2){

                 unlock.setVisibility(View.VISIBLE);
                 Ask.setVisibility(View.GONE);

                alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle("                                      Smart Parking");
                alertDialog.setMessage("             Wrong lot!!  please go to your lot....");
                alertDialog.show();
                TextView textView = (TextView) alertDialog.findViewById(android.R.id.message);
                textView.setTextSize(25);
                textView.setTextColor(Color.RED);
                 mStatus.setTextColor(Color.RED);

                 Ask.setVisibility(View.GONE);



            }


             //Parking
            else if (status == 0 && status_2a == 3){

                 unlock.setVisibility(View.VISIBLE);
                 Ask.setVisibility(View.GONE);

                 mStatus.setTextColor(Color.parseColor("#0dce5e"));
             }


             // getting out
            else if (status == 0 && status_2a == 4){

                 mStatus.setTextColor(Color.parseColor("#f9d540"));

             }

            else if (status == 1) {
                Toast.makeText(MainActivity.this, "Sorry the connection failed......" , Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }





    //show User info
    try {
        String resp = postM.postMain(ipParse,login_name);
        JSONObject object = new JSONObject();
        try {
            object = new JSONObject(resp);
            int status = object.getInt("status");
            if (status == 0) {

                mName.setText(object.getString ("name"));
                mUsername.setText(object.getString("username"));
                mLicense.setText(object.getString("license"));
                mLot.setText(object.getString("lot"));
                mStatus.setText(object.getString("user_status"));
                mDate.setText(object.getString("date"));
                mPayment.setText(object.getString("payment"));
                mTel.setText(object.getString("tel"));


            } else if (status == 1) {
                Toast.makeText(MainActivity.this, "Sorry something wrong..." , Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }





    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = getIntent();
            finish();
            startActivity(intent);

        }

    });

    Ask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AskFloor.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("username", login_name);
            intent.putExtra("license", user_license);
            intent.putExtra("lot", lot_lot);
            startActivity(intent);
        }

    });



    layout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Layout.class);
            startActivity(intent);

        }

    });

    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            loginManager.remove_ExistLogin();
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();

        }

    });




    unlock.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            unlock();

        }
    });


}


public void unlock(){
    PostFunction postM =new PostFunction();
    try {

        String resp = postM.postUnlock(ipParse ,login_name, user_license);
        JSONObject object = new JSONObject();
        try {
            object = new JSONObject(resp);
            int status = object.getInt("status");


            if (status == 0) {

                Toast.makeText(MainActivity.this, "UNLOCKED! thank you for coming......", Toast.LENGTH_LONG).show();
                Intent intent = getIntent();
                startActivity(intent);
                finish();


            } else if (status == 1) {
                Toast.makeText(MainActivity.this, "UNLOCK FAILED...", Toast.LENGTH_LONG).show();

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private class UpdateCountdownTask extends AsyncTask<Long, Long, Void> {
    @Override
    protected Void doInBackground(Long... millisUntilFinished) {
        CountDownTimer myCounter = new CountDownTimer(3600000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                publishProgress(millisUntilFinished);
            }
            @Override
            public void onFinish() {
                mTimer.setText("");
                unlock();
                mStatus.setTextColor(Color.parseColor("#f9d540"));
            }
        };
        myCounter.start();
        return null;
    }
    @Override
    protected void onProgressUpdate(Long... millisUntilFinished) {
        super.onProgressUpdate(millisUntilFinished);
        long millis = millisUntilFinished[0];
        mTimer.setText("" + String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
    }
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        mTimer.setText("");
    }
}


}

1 个答案:

答案 0 :(得分:0)

创建CountDown计时器: 使用静态变量,以便在Activity再次加载时不会启动:

static long v1=60000;
static long v2=1000;
    new CountDownTimer(v1, v2) {
        public void onTick(long millisUntilFinished) {
            /*for one second*/
            textViewFacebook.setText("seconds remaining: " + millisUntilFinished / v2);
            //here you can have your logic to set text to edittext
        }
        public void onFinish() {
            textViewFacebook.setText("done!");
        }
    }.start();

只需将此代码放入AsyncTask backgroud事件中即可在后台运行。