Android把延时器封装成全局方法——适合菜鸟使用
2017-12-18 15:23
225 查看
多的不说,直接上代码,复制粘贴直接能用的那种:
//在MainActivity中
//声明用到的控件
public static Timer mTimer_main = null;
public static TimerTask mTimerTask_main = null;
public static Context _context;
//在onCreate()中
_context=this;//获取上下文
//定义一个全局的定时器:
public static void dingshiqi(){
//非空判断 如果当前存在定时器,则cancel掉,保证当前只有一个定时器,防止出现定时器没关掉的情况
if(mTimerTask_main != null) {
mTimerTask_main.cancel();
}
if(mTimer_main != null) {
mTimer_main.cancel();
}
//每次都重新new一个定时器
mTimerTask_main = new TimerTask() {
@Override
public void run() {
//定时器做的操作,我这边做的是跳转activity
_intent = new Intent(_context, Dialog_view.class);//第一个参数是mainactivity, 第二个参数是目标activity
_context.startActivity(_intent);
}
};
//new一个timer
定时三十秒后做的操作
mTimer_main = new Timer();
mTimer_main.schedule(mTimerTask_main, 30000);//schedule启动定时器,第一个参数是需要做的操作,第二个参数是延时的时间,单位是毫秒
}
使用方法:
在当前activity中直接调用:dingshiqi();
在别的类中:MainActivity.dingshiqi();
说的这么详细都不懂的话就多看看基础吧。。。
//在MainActivity中
//声明用到的控件
public static Timer mTimer_main = null;
public static TimerTask mTimerTask_main = null;
public static Context _context;
//在onCreate()中
_context=this;//获取上下文
//定义一个全局的定时器:
public static void dingshiqi(){
//非空判断 如果当前存在定时器,则cancel掉,保证当前只有一个定时器,防止出现定时器没关掉的情况
if(mTimerTask_main != null) {
mTimerTask_main.cancel();
}
if(mTimer_main != null) {
mTimer_main.cancel();
}
//每次都重新new一个定时器
mTimerTask_main = new TimerTask() {
@Override
public void run() {
//定时器做的操作,我这边做的是跳转activity
_intent = new Intent(_context, Dialog_view.class);//第一个参数是mainactivity, 第二个参数是目标activity
_context.startActivity(_intent);
}
};
//new一个timer
定时三十秒后做的操作
mTimer_main = new Timer();
mTimer_main.schedule(mTimerTask_main, 30000);//schedule启动定时器,第一个参数是需要做的操作,第二个参数是延时的时间,单位是毫秒
}
使用方法:
在当前activity中直接调用:dingshiqi();
在别的类中:MainActivity.dingshiqi();
说的这么详细都不懂的话就多看看基础吧。。。
相关文章推荐
- android使用全局变量的方法
- android使用全局变量的两种方法
- android使用全局变量的两种方法
- android 开发零起步学习笔记(十九):android使用全局变量的两种方法
- Android中封装View提供接口供点击事件回调的方法及使用
- Android使用OkHttp实例,以及OkHttp方法封装
- android使用全局变量的两种方法
- 转:Android随笔之——使用Root权限实现后台模拟全局按键、触屏事件方法(类似按键精灵)
- android使用全局变量的两种方法
- 【Android数据传递】全局变量的使用方法(附源码)
- 最新google play内购(com.android.billingclient) 教程 代码 封装 使用方法
- Android使用OkHttp实例,以及OkHttp方法封装
- Android编程实现全局获取Context及使用Intent传递对象的方法详解
- [转]android使用全局变量的两种方法
- android使用全局变量的两种方法
- FE - Weex 使用简单封装数据加载插件为全局加载方法
- android使用全局变量的两种方法
- 【原创】不用封装jar包 直接引入工程使用的方法(类似android的 is Library功能)
- android使用全局变量的两种方法
- android使用全局变量的两种方法