由于handle与activity生命周期不同,所有如果以内部类的形式访问handler会导致handler一直占用activity的应用,导致activity无法销毁,解决方案:
Activity 里调用:
private final Handler handler = new MyHandler(AdvertingPageActivity.this, new MyHandlerInterface() {
@Override
public void goJump() {
ForLog.showError("--我收到通知了");
//do something
}
});
handler.sendEmptyMessageDelayed(0, 1000);
自定义handler类
package com.jiutouxiang.activity.login.adverting_page;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import com.jiutouxiang.R;
import com.jiutouxiang.toolkits.ForLog;
import java.lang.ref.WeakReference;
/**
* Created by Administrator on 2017/9/29 0029.
*/
public class MyHandler extends Handler {
private int count=3;
WeakReference<Activity> mActivityReference;
private MyHandlerInterface myHandlerInterface;
MyHandler(Activity activity ,MyHandlerInterface myHandlerInterface) {
ForLog.showError(activity.toString());
mActivityReference= new WeakReference<Activity>(activity);
this.myHandlerInterface=myHandlerInterface;
}
@Override
public void handleMessage(Message msg) {
final Activity activity = mActivityReference.get();
if (activity != null) {
if (msg.what == 0) {
TextView tv_title=(TextView)activity.findViewById(R.id.tv_title);
int i=getCount();
if(i==0){
ForLog.showError("---我要去跳转了");
myHandlerInterface.goJump();
return;
}else {
tv_title.setText("" +i);
this.sendEmptyMessageDelayed(0, 1000);
return;
}
}
}
ForLog.showError("---我要去跳转了");
myHandlerInterface.goJump();
return;
}
private int getCount(){
count--;
return count;
}
}
package com.jiutouxiang.activity.login.adverting_page;
/**
* Created by Administrator on 2017/9/29 0029.
*/
public interface MyHandlerInterface {
void goJump();
}