第一种方式
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="io.github.isayes.timecount.MainActivity">
<TextView
android:id="@+id/id_time_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorGray"
android:padding="4dp"
android:text="倒计时开始" />
</RelativeLayout>
package io.github.isayes.timecount;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int timeSecond = 4;
private TextView mTextView;
private TimeCount timeCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.id_time_count);
mTextView.setOnClickListener(mOnClickListener);
initData();
}
public View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
timeCount.start();
}
};
private void initData() {
timeCount = new TimeCount(5000, 1000);
}
// 倒计时内部类
class TimeCount extends CountDownTimer {
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
mTextView.setClickable(false);
String time = timeSecond-- + "";
mTextView.setText(time);
}
@Override
public void onFinish() {
mTextView.setText("倒计时完毕");
mTextView.setClickable(true);
timeSecond = 4;
}
}
}
第二种方式
利用handler.sendEmptyMessageDelayed(0, 1000);
public class LauncherActivity extends BaseActivity {
private WebView mWebView;
private TextView mTextView;
private ImageView mImageView;
private long mStartTime;
/* 广告倒计时数字提示初始值 */
private int timeSeconds = 4;
private boolean mHasDeal = false;
private boolean mIsRequestSession = false;
private Object mObj = new Object();
private HttpService mHttpService;
private ConfigHelper mConfigHelper;
private LauncherHandler launcherHandler;
private static final int BIND_TIME_OUT = 5000;
private static final int LAUNCHER_DURATION = 4000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
initView();
initData();
hideTitleBar();
attemptAutoLogin();
}
@Override
protected void onResume() {
super.onResume();
JPushInterface.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
JPushInterface.onPause(this);
}
private void initView() {
mTextView = (TextView) findViewById(R.id.textView);
mImageView = (ImageView) findViewById(R.id.id_ad_background);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.loadUrl(ServerConfig.POST_AD_URL);
mWebView.setWebViewClient(mWebViewClient);
}
private WebViewClient mWebViewClient = new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mImageView.setVisibility(View.GONE);
}
}, 1200);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loadLauncherContent();
}
};
private void initData() {
Intent intent = getIntent();
if (intent != null) {
mIsRequestSession = intent.getBooleanExtra("request_session", false);
}
mConfigHelper = ConfigHelper.getInstance();
mHttpService = new HttpService(this);
mStartTime = System.currentTimeMillis();
launcherHandler = new LauncherHandler();
}
/**
* 处理倒计时
*/
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
mTextView.setText(getCount());
handler.sendEmptyMessageDelayed(0, 1000);
}
}
};
/**
* 倒计时提示
* @return
*/
private String getCount() {
String time = "广告剩余 " + timeSeconds + " s";
if (timeSeconds == -1) {
mTextView.setBackgroundColor(Color.TRANSPARENT);
time = "";
}
timeSeconds--;
return time;
}
/**
* 对启动加载内容的选择
*/
private void loadLauncherContent() {
// 当有网络时 就正常加载 WebView 广告
if (CheckNetworkUtils.checkNetworkAvailable(this)) {
handler.sendEmptyMessageDelayed(0, 1000);
} else {
// 当没有网络的时候 就只加载欢迎图片
mImageView.setVisibility(View.VISIBLE);
}
}
/**
* 尝试自动登录
*/
private void attemptAutoLogin() {
if (mConfigHelper.isSavePassword()) {
login(mConfigHelper.getUserName(), mConfigHelper.getPassword());
} else {
OralTLApplication.getInstance().bindGuardService(this, new ServiceBindListener() {
@Override
public void setResult(IGuardService service) {
synchronized (mObj) {
boolean isLogin = false;
if (!mHasDeal) {
mHasDeal = true;
launcherHandler.removeMessages(2);
try {
isLogin = service.isLogin();
} catch (RemoteException e) {
e.printStackTrace();
}
if (isLogin) {
try {
String username = service.getUserName();
String password = service.getPassword();
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
login(username, password);
} else {
isLogin = false;
}
} catch (RemoteException e) {
e.printStackTrace();
isLogin = false;
}
}
}
if (!isLogin) {
sendHandleMessage(1, false, LAUNCHER_DURATION);
}
}
}
});
Message msg = Message.obtain();
msg.what = 2;
launcherHandler.sendMessageDelayed(msg, BIND_TIME_OUT);
}
}
private void sendHandleMessage(int what, boolean result, long delayMillis) {
Message msg = new Message();
msg.obj = result;
msg.what = what;
long duration = LAUNCHER_DURATION - delayMillis;
if (duration <= 0) {
launcherHandler.sendMessage(msg);
} else {
launcherHandler.sendMessageDelayed(msg, duration);
}
}
/**
* 向服务器发起登录请求
*
* @param username 用户名
* @param password 密码
*/
private void login(final String username, final String password) {
mHttpService.login(username, password, new HttpCallback() {
@Override
public void onHttpResult(boolean result, Object obj) {
long duration = System.currentTimeMillis() - mStartTime;
sendHandleMessage(1, result, duration);
}
});
}
public static void requestSession(Context context) {
Intent intent = new Intent(context, LauncherActivity.class);
intent.putExtra("request_session", true);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
private class LauncherHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
boolean result = (Boolean) msg.obj;
if (result) {
if (!mIsRequestSession) {
HomeActivity.startHomeActivity(LauncherActivity.this);
}
LauncherActivity.this.finish();
} else {
if (mIsRequestSession) {
LoginActivity.requestSession(LauncherActivity.this);
} else {
LoginActivity.startLoginActivity(LauncherActivity.this);
}
LauncherActivity.this.finish();
}
break;
case 2:
synchronized (mObj) {
if (!mHasDeal) {
mHasDeal = true;
sendHandleMessage(1, false, LAUNCHER_DURATION);
}
}
break;
default:
break;
}
}
}
}