2024字节跳动Android开发岗面试,关于Handler,面试官问了我这些……

  1. 如果你需要在Handler内部调用外部Activity的方法,你可以让这个Handler持有这个Activity的弱引用,这样便不会出现内存泄漏的问题了。

  2. 另外,对于匿名类Runnable,我们同样可以设置成静态的,因为静态内部类不会持有外部类的引用。

  3. 注意:如果使用Handler发送循环消息,最好是在Activity的OnDestroy方法中调用**mLeakHandler.removeCallbacksAndMessages(null);**移除消息。(这不是解决内存泄漏的方法)

5.两种解决办法如下:

弱引用(WeakReference)

public class SampleActivity extends Activity {

/**

  • Instances of static inner classes do not hold an implicit
  • reference to their outer class.
  • 弱引用的方式
    */
    private static class MyHandler extends Handler {
    private final WeakReference mActivity;
    public MyHandler(SampleActivity activity) {
    mActivity = new WeakReference(activity);
    }

@Override
public void handleMessage(Message msg) {
SampleActivity activity = mActivity.get();
if (activity != null) {
//to Something
}
}
}

静态

//定义成static的,因为静态内部类不会持有外部类的引用
private final MyHandler mHandler = new MyHandler(this);
private static final Runnable sRunnable = new Runnable() {
@Override
public void run() {//to something}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler.postDelayed(sRunnable, 1000 * 60 * 10);
finish();
}
}

面试官:为何主线程可以new Handler?如果想要在子线程中new Handler 要做些什么准备?

小王: 每一个handler必须要对应一个looper,主线程会自动创建Looper对象,不需要我们手动创建,所以主线程可以直接创建handler。

在new handler的时候没有传入指定的looper就会默认绑定当前创建handler的线程的looper,如果没有looper就报错。

因为在主线程中,Activity内部包含一个Looper对象,它会自动管理Looper,处理子线程中发送过来的消息。而对于子线程而言,没有任何对象帮助我们维护Looper对象,所以需要我们自己手动维护。 所以要在子线程开启Handler要先创建Looper,并开启Looper循环

如果在子线程中创建了一个Handler,那么就必须做三个操作:

  1. prepare();

  2. loop();

  3. quit();

面试官:子线程中维护的Looper,消息队列无消息的时候的处理方案是什么?有什么用?

小王: 在Handler机制里面有一个Looper,在Looper机制里面有一个函数,叫做quitSafely()和quit()函数,这两个函数是调用的MessageQueue的quit()。

/**

  • Quits the looper.
  • Causes the {@link #loop} method to terminate without processing any
  • more messages in the message queue.
  • Any attempt to post messages to the queue after the looper is asked to quit will fail.
  • For example, the {@link Handler#sendMessage(Message)} method will return false.
  • Using this method may be unsafe because some messages may not be delivered
  • before the looper terminates. Consider using {@link #quitSafely} instead to ensure
  • that all pending work is completed in an orderly manner.
  • @see #quitSafely
    */
    public void quit() {
    mQueue.quit(false);
    }

/**

  • Quits the looper safely.
  • Causes the {@link #loop} method to terminate as soon as all remaining messages
  • in the message queue that are already due to be delivered have been handled.
  • However pending delayed messages with due times in the future will not be
  • delivered before the loop terminates.
  • Any attempt to post messages to the queue after the looper is asked to quit will fail.
  • For example, the {@link Handler#sendMessage(Message)} method will return false.

*/
public void quitSafely() {
mQueue.quit(true);
}

再进入到MessageQueue的quit()函数。

void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException(“Main thread not allowed to quit.”);
}

synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;

if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}

// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}

它会remove消息,把消息队列中的全部消息给干掉。 把消息全部干掉,也就释放了内存

private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
removeAllMessagesLocked();
} else {
Message n;
for (;😉 {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}

而在quit()函数的最后一行,有一个nativeWake()函数。

// We can assume mPtr != 0 because mQuitting was previously false.

这个函数的调用,就会叫醒等待的地方,醒来之后,就接着往下执行。

//native的方法,在没有消息的时候回阻塞管道读取端,只有nativePollOnce返回之后才能往下执行
//阻塞操作,等待nextPollTimeoutMillis时长
nativePollOnce(ptr, nextPollTimeoutMillis);

往下执行后,发现 Message msg = mMessages; 是空的,然后就执行了这个,就接着往下走。

if (msg != null) {

} else {
// No more messages.
//没有消息,nextPollTimeoutMillis复位
nextPollTimeoutMillis = -1;
}

Millis);

往下执行后,发现 Message msg = mMessages; 是空的,然后就执行了这个,就接着往下走。

if (msg != null) {

} else {
// No more messages.
//没有消息,nextPollTimeoutMillis复位
nextPollTimeoutMillis = -1;
}

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值