Android Manifest.xml中application功能和重写

本文详细介绍了Android中如何利用Application类进行数据管理和传递,包括自定义Application类的方法、使用HashMap在不同组件间传递数据及缓存技巧。同时,还探讨了如何避免内存泄漏等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android:name属性是用来设置所有activity 属于哪个application的,默认是android.app.Application。

当然也可以自己定义一个类,例如:
public class TestApplication extends Application {}


这个类的作用是为了放一些全局的和一些上下文都要用到的变量和方法。
然后在AndroidManifest.xml中<application/>节点中添加android:name属性

<application android:icon="@drawable/icon"

   android:label="@string/app_name"

   android:name=".TestApplication">  

这样就可以将默认的Application给设置成我们自定义的TestApplication

这样处理的好处是:

继承的话,当应用程序退出后其生命周期也跟着结束,

而用静态类的话程序退出后不会立刻被gc回收,当你再次进入后会发现该静态类保存的信息状态是之前的。

有可能会导致程序不是你想要的初始化状态。

 

PS:TestApplication一定要指明类域为public,否则运行时候会报错找不到这个类。

即使写成这样:class TestApplication extends Application{}

也不可以,因为默认情况只是为包可见。


What is Application

Application和Activity,Service一样是android框架的一个系统组件,当android程序启动时系统会创建一个 application对象,用来存储系统的一些信息。通常我们是不需要指定一个Application的,这时系统会自动帮我们创建,如果需要创建自己 的Application,也很简单创建一个类继承 Application并在manifest的application标签中进行注册(只需要给Application标签增加个name属性把自己的 Application的名字定入即可)。

android系统会为每个程序运行时创建一个Application类的对象且仅创建一个所以Application可以说是单例 (singleton)模式的一个类.且application对象的生命周期是整个程序中最长的,它的生命周期就等于这个程序的生命周期。因为它是全局的单例的,所以在不同的Activity,Service中获得的对象都是同一个对象。所以通过Application来进行一些,数据传递,数据共享 等,数据缓存等操作。

 

Data passing between components using Application

假如有一个Activity A, 跳转到 Activity B ,并需要推荐一些数据,通常的作法是Intent.putExtra() 让Intent携带,或者有一个Bundle把信息加入Bundle让Intent推荐Bundle对象,实现传递。但这样作有一个问题在 于,Intent和Bundle所能携带的数据类型都是一些基本的数据类型,如果想实现复杂的数据传递就比较麻烦了,通常需要实现 Serializable或者Parcellable接口。这其实是Android的一种IPC数据传递的方法。如果我们的两个Activity在同一个 进程当中为什么还要这么麻烦呢,只要把需要传递的对象的引用传递过去就可以了。

基本思路是这样的。在Application中创建一个HashMap<String,Object> ,以字符串为索引Object为value这样我们的HashMap就可以存储任何类型的对象了。在Activity A中把需要传递的对象放入这个HashMap,然后通过Intent或者其它途经再把这人索引的字符串传递给Activity B ,Activity B 就可以根据这个字符串在HashMap中取出这个对象了。只要再向下转个型 ,就实现了对象的传递。

Data caching in Application

我一般会习惯在application中建立两个HashMap<String,Object>一个用于数据的传递,一个用于缓存一些数据。比如有一个Activity需要从网站获取一些数据,获取完之后我们就可以把这个数据cache到Application 当中,当页面设置到其它Activity再回来的时候,就可以直接使用缓存好的数据了。但如果需要cache一些大量的数据,最好是cache一些 (软引用)SoftReference ,并把这些数据cache到本地rom上或者sd卡上。如果在application中的缓存不存在,从本地缓存查找,如果本地缓存的数据也不存在再从网 络上获取。

PitFalls

使用Application如果保存了一些不该保存的对象很容易导致内存泄漏。如果在Application的oncreate中执行比较 耗时的操作,将直接影响的程序的启动时间。不些清理工作不能依靠onTerminate完成,因为android会尽量让你的程序一直运行,所以很有可能 onTerminate不会被调用。

MemoryLeak

在Java中内存泄漏是指,某个(某些)对象已经不在被使用应该被gc所回收,但有一个对象持有这个对象的引用而阻止这个对象被回收比如我 们通常会这样创建一个View TextView tv = new TextView(this);这里的this通常都是Activity。所以这个TextView就持有着这个Activity的引用。下面看张图 (Google IO 2011 ppt中抄得)

Android笔记 <wbr>Application对象的使用-数据传递以及内存泄漏问题

通常情况下,当用户转动手机的时候,android会重新调用OnCreate()方法生成一个新的Activity,原来的 Activity应该被GC所回收。但如果有个对象比如一个View的作用域超过了这个Activity(比如有一个static对象或者我们把这个 View的引用放到了Application当中),这时候原来的Activity将不能被GC所回收,Activity本身又持有很多对象的引用,所以 整个Activity的内存被泄漏了。

经常导致内存泄漏的一些原因:

keeping a long-lived reference to a Context.持有一个context的对象,从而gc不能回收。

1,一个View,的作用域超出了所在的Activity的作用域,比如一个static的View或者 把一个View cache到了application当中 etc

2,某些与View关联的Drawable的作用域超出了Activity的作用域。

3,Runnable对象:比如在一个Activity中启用了一个新线程去执行一个任务,在这期间这个Activity被系统回收了, 但Runnalbe的任务还没有执行完毕并持有Activity的引用而泄漏,但这种泄漏一般来泄漏一段时间,只有Runnalbe的线程执行完闭,这个 Activity又可以被正常回收了。

4,内存类的对象作用域超出Activity的范围:比如定义了一个内存类来存储数据,又把这个内存类的对象传给了其它Activity 或者Service等。因为内部类的对象会持有当前类的引用,所以也就持有了Context的引用。解决方法是如果不需要当前的引用把内部类写成 static或者,把内部类抽取出来变成一个单独的类,或者把避免内部对象作用域超出Activity的作用域。

out Of Memery Error 在android中每一个程序所分到的内存大小是有限的,如果超过了这个数就会报Out Of Memory Error。android给程序分配的内存大小与手机硬件有关,以下是一些手机的数据:

G1:16M Droid:24 Nexus One:32M Xoom:48Ms

所以尽量把程序中的一些大的数据cache到本地文件。以免内存使用量超标。

Snippets

1,通过Application在两个Activity间传递数据

Android笔记 <wbr>Application对象的使用-数据传递以及内存泄漏问题  Android笔记 <wbr>Application对象的使用-数据传递以及内存泄漏问题

记得数据传递完成之后,把存放在application的HashMap中的数据remove掉,以免发生内存的泄漏。

 

 

其实我们开发的每个android应用程序就是一个Appliction,定义这个类往往是在AndroidManifes.xml中用到。例如:

 

<application android:icon="@drawable/icon"

    android:label="@string/app_name"

    android:name=".MyApplication">
 
这里定义了我们整个应用程序的属性,例如名称和图标。
我们可以自定义Appliction,例如:
public class MyApplication extends Application {

}
就是这儿,将我们以前一直用的默认Application给他设置成我们自己做的MyApplication
MyApplication类的作用是为了放一些全局的和一些上下文都要用到变量和方法之类的。


Executing tasks: [:app:assembleDebug] in project D:\TestProject\MyApplication > Task :app:createDebugVariantModel UP-TO-DATE > Task :app:preBuild UP-TO-DATE > Task :app:preDebugBuild UP-TO-DATE > Task :app:mergeDebugNativeDebugMetadata NO-SOURCE > Task :app:compileDebugAidl NO-SOURCE > Task :app:compileDebugRenderscript NO-SOURCE > Task :app:generateDebugBuildConfig UP-TO-DATE > Task :app:javaPreCompileDebug UP-TO-DATE > Task :app:checkDebugAarMetadata UP-TO-DATE AGPBI: {"kind":"warning","text":"Your project has set `android.useAndroidX=true`, but configuration `:app:debugRuntimeClasspath` still contains legacy support libraries, which may cause runtime issues.\nThis behavior will not be allowed in Android Gradle plugin 8.0.\nPlease use only AndroidX dependencies or set `android.enableJetifier=true` in the `gradle.properties` file to migrate your project to AndroidX (see https://developer.android.com/jetpack/androidx/migrate for more info).\nThe following legacy support libraries are detected:\n:app:debugRuntimeClasspath -> com.android.support:support-compat:28.0.0\n:app:debugRuntimeClasspath -> com.android.support:support-compat:28.0.0 -> com.android.support:support-annotations:28.0.0\n:app:debugRuntimeClasspath -> com.android.support:support-compat:28.0.0 -> com.android.support:collections:28.0.0\n:app:debugRuntimeClasspath -> com.android.support:support-compat:28.0.0 -> android.arch.lifecycle:runtime:1.1.1\n:app:debugRuntimeClasspath -> com.android.support:support-compat:28.0.0 -> android.arch.lifecycle:runtime:1.1.1 -> android.arch.lifecycle:common:1.1.1\n:app:debugRuntimeClasspath -> com.android.support:support-compat:28.0.0 -> android.arch.lifecycle:runtime:1.1.1 -> android.arch.core:common:1.1.1\n:app:debugRuntimeClasspath -> com.android.support:support-compat:28.0.0 -> com.android.support:versionedparcelable:28.0.0","sources":[{}]} > Task :app:generateDebugResValues UP-TO-DATE > Task :app:mapDebugSourceSetPaths UP-TO-DATE > Task :app:generateDebugResources UP-TO-DATE > Task :app:mergeDebugResources UP-TO-DATE > Task :app:packageDebugResources UP-TO-DATE > Task :app:parseDebugLocalResources UP-TO-DATE > Task :app:createDebugCompatibleScreenManifests UP-TO-DATE > Task :app:extractDeepLinksDebug UP-TO-DATE > Task :app:processDebugMainManifest FAILED [androidx.versionedparcelable:versionedparcelable:1.1.1] C:\Users\wangsen\.gradle\caches\transforms-3\4b621581b14be943fef7e9025808a5ef\transformed\versionedparcelable-1.1.1\AndroidManifest.xml Warning: Namespace 'androidx.versionedparcelable' used in: androidx.versionedparcelable:versionedparcelable:1.1.1, com.android.support:versionedparcelable:28.0.0. D:\TestProject\MyApplication\app\src\main\AndroidManifest.xml:22:18-91 Error: Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91 is also present at [androidx.core:core:1.7.0] AndroidManifest.xml:24:18-86 value=(androidx.core.app.CoreComponentFactory). Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:7:5-25:19 to override. See https://developer.android.com/r/studio-ui/build/manifest-merger for more information about the manifest merger. > Task :app:mergeDebugShaders UP-TO-DATE > Task :app:compileDebugShaders NO-SOURCE > Task :app:generateDebugAssets UP-TO-DATE > Task :app:mergeDebugAssets UP-TO-DATE > Task :app:compressDebugAssets UP-TO-DATE > Task :app:processDebugJavaRes NO-SOURCE > Task :app:desugarDebugFileDependencies UP-TO-DATE > Task :app:mergeDebugJniLibFolders UP-TO-DATE > Task :app:mergeDebugNativeLibs NO-SOURCE > Task :app:stripDebugDebugSymbols NO-SOURCE > Task :app:validateSigningDebug UP-TO-DATE > Task :app:writeDebugAppMetadata UP-TO-DATE > Task :app:writeDebugSigningConfigVersions UP-TO-DATE > Task :app:checkDebugDuplicateClasses FAILED > Task :app:mergeDebugJavaResource FAILED FAILURE: Build completed with 3 failures. 1: Task failed with an exception. ----------- * What went wrong: Execution failed for task ':app:processDebugMainManifest'. > Manifest merger failed with multiple errors, see logs * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. ============================================================================== 2: Task failed with an exception. ----------- * What went wrong: Execution failed for task ':app:checkDebugDuplicateClasses'. > A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable > Duplicate class android.support.v4.app.INotificationSideChannel found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.app.INotificationSideChannel$Stub found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.app.INotificationSideChannel$Stub$Proxy found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.graphics.drawable.IconCompatParcelizer found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.os.IResultReceiver found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.os.IResultReceiver$Stub found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.os.IResultReceiver$Stub$Proxy found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.os.ResultReceiver found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.os.ResultReceiver$1 found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.os.ResultReceiver$MyResultReceiver found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class android.support.v4.os.ResultReceiver$MyRunnable found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class androidx.core.graphics.drawable.IconCompatParcelizer found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class androidx.core.internal.package-info found in modules core-1.7.0-runtime (androidx.core:core:1.7.0) and support-compat-28.0.0-runtime (com.android.support:support-compat:28.0.0) Duplicate class androidx.versionedparcelable.CustomVersionedParcelable found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.NonParcelField found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.ParcelField found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.ParcelImpl found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.ParcelImpl$1 found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.ParcelUtils found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.VersionedParcel found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.VersionedParcel$1 found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.VersionedParcel$ParcelException found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.VersionedParcelParcel found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.VersionedParcelStream found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.VersionedParcelStream$FieldBuffer found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.VersionedParcelable found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Duplicate class androidx.versionedparcelable.VersionedParcelize found in modules versionedparcelable-1.1.1-runtime (androidx.versionedparcelable:versionedparcelable:1.1.1) and versionedparcelable-28.0.0-runtime (com.android.support:versionedparcelable:28.0.0) Go to the documentation to learn how to <a href="d.android.com/r/tools/classpath-sync-errors">Fix dependency resolution errors</a>. * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. ============================================================================== 3: Task failed with an exception. ----------- * What went wrong: Execution failed for task ':app:mergeDebugJavaResource'. > A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction > 2 files found with path 'META-INF/androidx.core_core.version' from inputs: - C:\Users\wangsen\.gradle\caches\transforms-3\0b22a6b07b3e498281e2fdb9d93c9c6b\transformed\support-compat-28.0.0\jars\classes.jar - C:\Users\wangsen\.gradle\caches\transforms-3\0212d0c0c0b99c5d00c15a82a811f4d1\transformed\core-1.7.0\jars\classes.jar Adding a packagingOptions block may help, please refer to https://developer.android.com/reference/tools/gradle-api/7.4/com/android/build/api/dsl/ResourcesPackagingOptions for more information * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. ============================================================================== * Get more help at https://help.gradle.org BUILD FAILED in 436ms 22 actionable tasks: 3 executed, 19 up-to-date
最新发布
07-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值