1. 程式人生 > >倒計時及預設第二次不進入該頁面

倒計時及預設第二次不進入該頁面

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

ImageView img;
TextView tv;
SharedPreferences sharedPreferences;
int time=3;

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

    tv = findViewById(R.id.tv);

    handler.sendEmptyMessageDelayed(1,1000);

    //預設第二次不顯示
     sharedPreferences = getSharedPreferences("qmy", MODE_PRIVATE);
    boolean isfinish = sharedPreferences.getBoolean("isfinish", false);
    if (isfinish){
        startActivity(new Intent(MainActivity.this,show.class));
        finish();
    }
}
Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        time--;
        if (time<=0){
            SharedPreferences.Editor edit = sharedPreferences.edit();

            edit.putBoolean("isfinish",true);
            edit.commit();

            startActivity(new Intent(MainActivity.this,show.class));

        }else {
            tv.setText(time+"");
            handler.sendEmptyMessageDelayed(1,1000);
        }
    }
};

@Override
protected void onDestroy() {
    if (handler!=null) {
        handler.removeMessages(1);
        handler=null;
    }
    super.onDestroy();
}

}