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);

    }

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

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • web是什么?_怎么进入web界面

    web是什么?_怎么进入web界面我也是从接触Web这个词开始就一直搞不清和Internet之间是什么关系。说说我理解的Web,可能很多地方不准确.Web就是在Http协议基础之上,利用浏览器进行访问的网站.WebPage指

    2022年8月2日
    14
  • RegisterStartupScript和RegisterClientScriptBlock

    RegisterStartupScript和RegisterClientScriptBlockPage.Response.Write(“varresponse;”);    Page.RegisterStartupScript(“RegisterStartupScript”,”varRegisterStartupScript;”);    Page.RegisterClientScriptBlock(“RegisterClientScriptBlock”,”varRe

    2022年7月20日
    13
  • 如何开发一款游戏:游戏开发流程及所需工具

    如何开发一款游戏:游戏开发流程及所需工具本文来自作者goto先生在GitChat上分享「如何开发一款游戏:游戏开发流程及所需工具」,「阅读原文」查看交流实录。「文末高能」编辑|哈比游戏作为娱乐生活的一个方面,参与其中的人越来越多,而大部分参与其中的人都是以玩家的身份。他们热爱一款游戏,或是被游戏的故事情节、炫丽的场景、动听的音乐所艳羡,亦或是被游戏中角色扮演、炫酷的技能、有趣的任务所吸引,然而他们中的大多数可能并不了解如此

    2022年4月29日
    67
  • django框架菜鸟教程_django框架菜鸟教程

    django框架菜鸟教程_django框架菜鸟教程Django一、介绍1、简介是用python语言写的开源web开发框架,并遵循MVC设计。Django的主要目的是简便、快速的开发数据库驱动的网站。2、特点1)重量级框架2)MVT模式MVC其核心思想是分工、解耦,让不同的代码块之间降低耦合,增强代码的可扩展性和可移植性,实现向后兼容。M全拼为Model,主要封装对数据库层的访问,对数据库中的数据进行增、删、改、查操作。…

    2022年9月8日
    0
  • 获取activexobject对象失败_在各种管理对象中最重要的是

    获取activexobject对象失败_在各种管理对象中最重要的是JavaScript中ActiveXObject对象是启用并返回Automation对象的引用

    2022年10月14日
    0
  • R、RStudio下载与安装方法

    R、RStudio下载与安装方法现如今,R语言是统计领域广泛使用的工具,是属于GNU系统的一个自由、免费、源代码开放的软件,是用于统计计算和统计绘图的优秀工具。而RStudio是R的集成开发环境,用它进行R编程的学习和实践会更加轻松和方便。下面就教大家如何下载并安装R和RStudio,比较简单。R的维护工作由一个国际化的开发者团队负责。R软件的官方下载页面叫作TheComprehensiveRArchiveNetwor…

    2022年6月30日
    44

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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