Activity中bindService和registerReceiver的清理工作[通俗易懂]

Activity中bindService和registerReceiver的清理工作[通俗易懂]在Android开发中,我们经常需要注册BroadcastReceiver和bindservice。接口函数如下:publicIntentregisterReceiver(BroadcastReceiverreceiver,IntentFilterfilter);publicvoidunregisterReceiver(BroadcastReceiverrecei

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

在Android开发中,我们经常需要注册BroadcastReceiver和bind service。

接口函数如下:

public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter);

public void unregisterReceiver(BroadcastReceiver receiver);

public boolean bindService(Intent service, ServiceConnection conn, int flags);

public void unbindService(ServiceConnection conn);


有的时候,用户只调用了注册函数,或者是bind service,而忘记了unregisterReceiver和unbindService。这时,在Activity退出的时候,会自动这些问题,自动调用unregisterReceiver和unbindService。具体的流程如下:

    private void handleDestroyActivity(IBinder token, boolean finishing,
            int configChanges, boolean getNonConfigInstance) {

        ActivityClientRecord r = performDestroyActivity(token, finishing,
                configChanges, getNonConfigInstance);        回调Activity的onDestroy
        if (r != null) {

            // Mocked out contexts won’t be participating in the normal
            // process lifecycle, but if we’re running with a proper
            // ApplicationContext we need to have it tear down things
            // cleanly.
            Context c = r.activity.getBaseContext();
            if (c instanceof ContextImpl) {

                ((ContextImpl) c).scheduleFinalCleanup(
                        r.activity.getClass().getName(), “Activity”);     清理 注册的receiver和bind的service
            }
        }
        if (finishing) {

            try {

                ActivityManagerNative.getDefault().activityDestroyed(token);      通知AMS,activity已经destroy
            } catch (RemoteException ex) {

                // If the system process has died, it’s game over for everyone.
            }
        }
        mSomeActivitiesChanged = true;
    }

In ContextImpl.java

    final void scheduleFinalCleanup(String who, String what) {

        mMainThread.scheduleContextCleanup(this, who, what);
    }

In ActivityThread.java

    final void scheduleContextCleanup(ContextImpl context, String who,
            String what) {

        ContextCleanupInfo cci = new ContextCleanupInfo();
        cci.context = context;
        cci.who = who;
        cci.what = what;
        sendMessage(H.CLEAN_UP_CONTEXT, cci);
    }

                case CLEAN_UP_CONTEXT:
                    ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
                    cci.context.performFinalCleanup(cci.who, cci.what);
                    break;


In ContextImpl.java

    final void performFinalCleanup(String who, String what) {

        //Log.i(TAG, “Cleanup up context: ” + this);
        mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
    }

In LoadedApk.java

    public void removeContextRegistrations(Context context,
            String who, String what) {

        final boolean reportRegistrationLeaks = StrictMode.vmRegistrationLeaksEnabled();
        ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> rmap =  mReceivers.remove(context);
        if (rmap != null) {

            for (int i=0; i<rmap.size(); i++) {      清理所有已经注册的receiver
                LoadedApk.ReceiverDispatcher rd = rmap.valueAt(i);
                IntentReceiverLeaked leak = new IntentReceiverLeaked(
                        what + ” ” + who + ” has leaked IntentReceiver “
                        + rd.getIntentReceiver() + ” that was ” +
                        “originally registered here. Are you missing a ” +
                        “call to unregisterReceiver()?”);
                leak.setStackTrace(rd.getLocation().getStackTrace());
                Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
                if (reportRegistrationLeaks) {

                    StrictMode.onIntentReceiverLeaked(leak);
                }
                try {

                    ActivityManagerNative.getDefault().unregisterReceiver(
                            rd.getIIntentReceiver());
                } catch (RemoteException e) {

                    // system crashed, nothing we can do
                }
            }
        }
        mUnregisteredReceivers.remove(context);
        //Slog.i(TAG, “Receiver registrations: ” + mReceivers);

        ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> smap =
            mServices.remove(context);
        if (smap != null) {

            for (int i=0; i<smap.size(); i++) {         解绑定已经bind的service
                LoadedApk.ServiceDispatcher sd = smap.valueAt(i);
                ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
                        what + ” ” + who + ” has leaked ServiceConnection “
                        + sd.getServiceConnection() + ” that was originally bound here”);
                leak.setStackTrace(sd.getLocation().getStackTrace());
                Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
                if (reportRegistrationLeaks) {

                    StrictMode.onServiceConnectionLeaked(leak);
                }
                try {

                    ActivityManagerNative.getDefault().unbindService(
                            sd.getIServiceConnection());
                } catch (RemoteException e) {

                    // system crashed, nothing we can do
                }
                sd.doForget();
            }
        }
        mUnboundServices.remove(context);
        //Slog.i(TAG, “Service registrations: ” + mServices);

    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/195003.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 0基础激光切割怎么学_吉他入门零基础视频教程

    0基础激光切割怎么学_吉他入门零基础视频教程杂谈最近有几个人加我,都说是刚开始学激光slam,基本都是研一,情况也都差不多,有的是课题组里只有自己做slam,有的是完全没人带,自己也没有基础.仔细想一想,其实入门slam真是个不容易的事.首先,编程语言,大多数使用c++,少数用python,c++你得至少能写个小demo吧.知道了如何写c++,还要准备编译环境吧,由于编译以及依赖等问题,做slam基本都用linux,还得知道如何使用ubuntu的命令行,知道怎么编译代码.关于机器人相关的大部分代码都使用ros做接口,因为接口统一,使用方式统

  • 为有机会进大厂,程序员必须掌握的核心算法有哪些?

    由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过…

  • win10怎么安装python3.8_win10怎么安装python

    win10怎么安装python3.8_win10怎么安装python更新提醒:本文已过期,PyTorch0.4.0已经有官方的Windows支持,Windows下安装最新的PyTorch0.4.0请移步本人另一篇博客:Windows下安装PyTorch0.4.0。2017年1月18日,周董生日这一天,facebook下的torch7团队宣布Pytorch开源,官网地址:pytorch。pytorch是一个python优先的深度学习框架,是一个和tensorfl…

  • 面试题:线程池处理流程 没用

    面试题:线程池处理流程 没用

  • android textwatcher 获取当前控件,android api解析之TextWatcher

    开发android有几年了,但是从来没有整理过,一直是写写写.从今天起开始慢慢整理,总结之处如有错误请指出,谢谢TextWatcher在什么时候会被调用?TextWatcher在edittext内容发生变化时会被调用TextWatcher一共有三个方法beforeTextChanged(CharSequences,intstart,intcount,intafter)在文本变化前调用…

  • pycharm突然打不开到底什么情况_pycharm运行没反应

    pycharm突然打不开到底什么情况_pycharm运行没反应当无法打开pycharm终端,出现以下情况1、打开pycharm设置2、打开一下界面3、在shell路径中选择windows下的cmd.exe,这样就可以将cmd命令路径连接到pycharm中,无法打开windows终端即可方便下载安装包4、重新启动pycharm…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号