项目中有个改密流程,忘记密码->手机号验证->新密码,要求验证手机号验证界面跳转或返回,再进入界面,60S内不再自动请求验证码。
最终解决方法为开启服务实现,倒计时结束后服务自动停止。
step 1:
创建服务
public class TimerService extends Service {
private Timer timer = null;
private TimerTask timerTask = null;
private int i = 0;
public static final String TIMER_ACTION = "your_package.timer";
@Override
public void onCreate() {
super.onCreate();
//在创建service的时候开始计时
if (timer == null && timerTask == null) {
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
i++;
//没执行一次就发送一次广播
Intent intent = new Intent();
intent.putExtra("time", i);
intent.setAction(TimerService.TIMER_ACTION);
sendBroadcast(intent);
}
};
timer.schedule(timerTask, 0, 1000);
}
}
@Override
public void onDestroy() {
super.onDestroy();
Logger.e("onDestroy");
if (timerTask != null) {
timerTask.cancel();
timerTask = null;
}
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
step 2:
定义广播
public class TimerReceiver extends BroadcastReceiver {
//必须要重载的方法,用来监听是否有广播发送
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (TimerService.TIMER_ACTION.equals(intentAction)) {
int time = intent.getIntExtra("time", 0);
}
}
}
step 3:
调用
//注册广播
timerReceiver = new TimerReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(TimerService.TIMER_ACTION);
registerReceiver(timerReceiver, filter);
//开始服务
startService(new Intent(mActivity, TimerService.class));
另附服务是否运行判断工具
/**
* 判断服务是否正在运行
*
*/
public static boolean isServiceRunning(String serviceName, Context context) {
//活动管理器
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(100); //获取运行的服务,参数表示最多返回的数量
for (ActivityManager.RunningServiceInfo runningServiceInfo : runningServices) {
String className = runningServiceInfo.service.getClassName();
if (className.equals(serviceName)) {
return true; //判断服务是否运行
}
}
return false;
}