Android和内存泄漏
我很担心从泄漏的金丝雀那里得到的信息。它表明,用户界面上声明的所有变量,如片段中的材质按钮、材质卡片视图、文本视图、图像视图等,都会导致内存泄漏。我不知道为什么会这样 例如,泄漏金丝雀将在材质按钮中拾取1个内存泄漏。当我在修复它的onDestroyView()中将材质按钮声明为null时。但是,leak canary将出现下一个UI变量,我必须在onDestroyView()中将UI中的每个变量声明为null,以阻止该片段泄漏 当然,在ondestroyView()方法中必须将所有声明的变量都设为null不是正常的做法,这将非常整洁。我原以为当我们看到一个新的片段时,android会处理好这些事情Android和内存泄漏,android,android-layout,android-fragments,leakcanary,Android,Android Layout,Android Fragments,Leakcanary,我很担心从泄漏的金丝雀那里得到的信息。它表明,用户界面上声明的所有变量,如片段中的材质按钮、材质卡片视图、文本视图、图像视图等,都会导致内存泄漏。我不知道为什么会这样 例如,泄漏金丝雀将在材质按钮中拾取1个内存泄漏。当我在修复它的onDestroyView()中将材质按钮声明为null时。但是,leak canary将出现下一个UI变量,我必须在onDestroyView()中将UI中的每个变量声明为null,以阻止该片段泄漏 当然,在ondestroyView()方法中必须将所有声明的变量都设
private Window mWindow;
private Toolbar mToolbar;
private FloatingActionButton btnBack, btnNext;
private Button btnStart;
private TextView tvSetUpNotifications, tvTitle, tvDescription;
private ImageView ivToolbar;
private CardView cvNotification;
private Bundle args = new Bundle();
private NavController mNavController;
private View view;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
((BaseApplication) getActivity().getApplication()).getAppComponent().inject(this);
}
public WorkoutCheckInIntro() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_workout_checkin_intro, container, false);
// configure the Window variable to enable the colour to be set
mWindow = getActivity().getWindow();
mWindow.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
mWindow.setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.calm));
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Instantiate the Navigation Controller.
mNavController = Navigation.findNavController(view);
// Configure the bottom navbar
BottomNavigationView navBar = getActivity().findViewById(R.id.bottom_navigation);
navBar.setVisibility(View.VISIBLE);
// Method calls
assignVariables();
setOnClickListeners();
}
/**
* Method which assigns variables to elements in the XML file.
*/
private void assignVariables() {
// Initialising variables from the xml file.
btnStart = view.findViewById(R.id.checkInDailyButtonStart);
tvSetUpNotifications = view.findViewById(R.id.setUpNotificationsTextView);
cvNotification = view.findViewById(R.id.notification_cardView2);
// Configure the top toolbar
mToolbar = view.findViewById(R.id.toolbar_check_in_intro);
btnBack = mToolbar.findViewById(R.id.toolbar_back_button);
btnNext = mToolbar.findViewById(R.id.toolbar_next_button);
btnNext.hide();
tvTitle = mToolbar.findViewById(R.id.toolbar_workout_title);
tvTitle.setVisibility(View.VISIBLE);
tvTitle.setTextColor(ContextCompat.getColor(getActivity(), R.color.white));
tvTitle.setText(getString(R.string.check_in));
tvDescription = mToolbar.findViewById(R.id.toolbar_workout_description);
tvDescription.setVisibility(View.GONE);
tvDescription.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
ivToolbar = mToolbar.findViewById(R.id.toolbar_workout_background);
ivToolbar.setVisibility(View.VISIBLE);
ivToolbar.setImageResource(R.drawable.check_in_intro);
}
/**
* Method which sets onClickListeners to buttons
*/
private void setOnClickListeners() {
btnStart.setOnClickListener(this);
btnBack.setOnClickListener(this);
tvSetUpNotifications.setOnClickListener(this);
cvNotification.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.toolbar_back_button:
if (mNavController.getCurrentDestination().getId() == R.id.workoutCheckInIntro) {
mNavController.navigate(R.id.action_workoutCheckInIntro_to_workoutFragment);
}
break;
case R.id.checkInDailyButtonStart:
// Boolean used in the WorkoutCheckInDailyMood.Class so when the user clicks
// the back button it will return them to this activity.
args.putBoolean(WORKOUT_CHECKIN_DAILY_MOOD, true);
if (mNavController.getCurrentDestination().getId() == R.id.workoutCheckInIntro) {
mNavController.navigate(R.id.action_workoutCheckInIntro_to_workoutMood, args);
}
break;
case R.id.notification_cardView2:
// Boolean used in the NotificationsSetUp.Class so when the user clicks
// the back button it will return them to this activity.
args.putBoolean(RETURN_TO_CHECKIN_WORKOUT, true);
if (mNavController.getCurrentDestination().getId() == R.id.workoutCheckInIntro) {
mNavController.navigate(R.id.action_workoutCheckInIntro_to_notificationsSetUp, args);
}
break;
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
mToolbar = null;
view = null;
btnBack = null;
btnNext = null;
tvDescription = null;
tvTitle = null;
ivToolbar = null;
btnStart = null;
cvNotification = null;
tvSetUpNotifications = null;
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:fillViewport="true"
tools:context=".ui.workouts.checkin.WorkoutCheckInIntro">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<include
android:id="@+id/toolbar_check_in_intro"
layout="@layout/toolbar_workout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="20dp"
android:text="Workout Length"
android:textSize="@dimen/text_size_heading_16sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar_check_in_intro" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="20dp"
android:text="3 MIN - 5 MIN"
android:textSize="@dimen/text_size_timer"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="20dp"
android:lineSpacingExtra="5sp"
android:text="We recommend to do this workout daily to develop a habit to check in with yourself each day. This is helpful as many of us are so busy that we become disconnected from our own thoughts and emotions."
android:textSize="@dimen/text_size_normal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2" />
<com.google.android.material.button.MaterialButton
android:id="@+id/checkInDailyButtonStart"
style="@style/btnStyleRed"
android:layout_width="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:text="Start"
app:icon="@drawable/ic_dumb_bell_white_16dp"
app:iconGravity="textStart"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/notification_cardView2"
app:layout_constraintVertical_bias="1.0"
/>
<com.google.android.material.card.MaterialCardView
android:id="@+id/notification_cardView2"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="32dp"
android:clickable="true"
app:cardCornerRadius="10dp"
app:cardElevation="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/setUpNotificationsTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="32dp"
android:gravity="center"
android:text="Set up daily notifications to remind you to check-in"
android:textColor="@color/colorPrimary"
android:textSize="@dimen/text_size_normal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/appCompatImageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:adjustViewBounds="true"
app:srcCompat="@drawable/brain_insight"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/setUpNotificationsTextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
───
│ GC Root: System class
│
├─ android.provider.FontsContract class
│ Leaking: NO (BaseApplication↓ is not leaking and a class is never leaking)
│ ↓ static FontsContract.sContext
├─ com.example.BaseApplication instance
│ Leaking: NO (WorkoutFragment↓ is not leaking and Application is a singleton)
│ ↓ BaseApplication.appComponent
├─ com.example.di.DaggerAppComponent instance
│ Leaking: NO (WorkoutFragment↓ is not leaking)
│ ↓ DaggerAppComponent.provideWorkoutAdapterProvider
├─ dagger.internal.DoubleCheck instance
│ Leaking: NO (WorkoutFragment↓ is not leaking)
│ ↓ DoubleCheck.instance
├─ com.example.adapters.RvAdapterWorkout instance
│ Leaking: NO (WorkoutFragment↓ is not leaking)
│ ↓ RvAdapterWorkout.mOnWorkoutListener
├─ com.example.ui.workouts.WorkoutFragment instance
│ Leaking: NO (WorkoutCheckInIntro↓ is not leaking and Fragment#mFragmentManager is not null)
│ ↓ WorkoutFragment.mFragmentManager
├─ androidx.fragment.app.FragmentManagerImpl instance
│ Leaking: NO (WorkoutCheckInIntro↓ is not leaking)
│ ↓ FragmentManagerImpl.mFragmentStore
├─ androidx.fragment.app.FragmentStore instance
│ Leaking: NO (WorkoutCheckInIntro↓ is not leaking)
│ ↓ FragmentStore.mActive
├─ java.util.HashMap instance
│ Leaking: NO (WorkoutCheckInIntro↓ is not leaking)
│ ↓ HashMap.table
├─ java.util.HashMap$Node[] array
│ Leaking: NO (WorkoutCheckInIntro↓ is not leaking)
│ ↓ HashMap$Node[].[3]
├─ java.util.HashMap$Node instance
│ Leaking: NO (WorkoutCheckInIntro↓ is not leaking)
│ ↓ HashMap$Node.value
├─ androidx.fragment.app.FragmentStateManager instance
│ Leaking: NO (WorkoutCheckInIntro↓ is not leaking)
│ ↓ FragmentStateManager.mFragment
├─ com.example.ui.workouts.checkin.WorkoutCheckInIntro instance
│ Leaking: NO (Fragment#mFragmentManager is not null)
│ ↓ WorkoutCheckInIntro.view
│ ~~~~
╰→ androidx.core.widget.NestedScrollView instance
Leaking: YES (ObjectWatcher was watching this because com.example.ui.workouts.checkin.WorkoutCheckInIntro received Fragment#onDestroyView() callback (references to its views should be cleared to prevent leaks))
key = 53dc4388-0db6-402a-9ee3-2db6617c98f5
watchDurationMillis = 192734
retainedDurationMillis = 187732
mContext instance of com.example.ui.main.MainActivity with mDestroyed = false
View#mParent is null
View#mAttachInfo is null (view detached)
View.mWindowAttachCount = 1
METADATA
Build.VERSION.SDK_INT: 30
Build.MANUFACTURER: Google
LeakCanary version: 2.4
App process name: com.
Analysis duration: 22667 ms
23 Leaks
┬───
│ GC Root: System class
│
├─ android.provider.FontsContract class
│ Leaking: NO (BaseApplication↓ is not leaking and a class is never leaking)
│ ↓ static FontsContract.sContext
├─ com.example.BaseApplication instance
│ Leaking: NO (Application is a singleton)
│ ↓ BaseApplication.appComponent
│ ~~~~~~~~~~~~
├─ com.example.di.DaggerAppComponent instance
│ Leaking: UNKNOWN
│ ↓ DaggerAppComponent.viewModelUsersProvider
│ ~~~~~~~~~~~~~~~~~~~~~~
├─ dagger.internal.DoubleCheck instance
│ Leaking: UNKNOWN
│ ↓ DoubleCheck.instance
│ ~~~~~~~~
╰→ com.example.persistence.viewmodel.ViewModelUsers instance
Leaking: YES (ObjectWatcher was watching this because com.example.persistence.viewmodel.ViewModelUsers received ViewModel#onCleared() callback)
key = 45b732d9-f6e0-4852-9b3c-8397c587f29f
watchDurationMillis = 223094
retainedDurationMillis = 218094
METADATA
Build.VERSION.SDK_INT: 30
Build.MANUFACTURER: Google
LeakCanary version: 2.4
App process name: com.
Analysis duration: 22667 ms
私有窗口mWindow;
私有工具栏mToolbar;
专用浮动操作按钮btnBack,btnNext;
私人按钮btnStart;
私有文本视图tvSetUpNotifications、tvTitle、tvDescription;
私有图像视图工具栏;
私家卡浏览通知;
私有Bundle args=新Bundle();
专用导航控制器;
私人视野;
@凌驾
public void onAttach(@NonNull上下文){
super.onAttach(上下文);
((BaseApplication)getActivity().getApplication()).getAppComponent().inject(此);
}
公共训练checkinintro(){
//必需的空公共构造函数
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图=充气机。充气(R.layout.fragment\u workout\u checkin\u intro,container,false);
//配置窗口变量以启用要设置的颜色
mWindow=getActivity().getWindow();
mWindows.clearFlags(WindowManager.LayoutParams.FLAG_半透明_状态);
mWindow.addFlags(WindowManager.LayoutParams.FLAG\u绘图\u系统\u栏\u背景);
mWindow.setStatusBarColor(ContextCompat.getColor(getActivity(),R.color.calme));
返回视图;
}
@凌驾
已创建公用void onview(@NonNull视图,@Nullable Bundle savedInstanceState){
super.onViewCreated(视图,savedInstanceState);
//实例化导航控制器。
mNavController=Navigation.findNavController(视图);
//配置底部导航栏
BottomNavigationView导航栏=getActivity().findViewById(R.id.bottom\u导航);
navBar.setVisibility(View.VISIBLE);
//方法调用
赋值变量();
setOnClickListeners();
}
/**
*方法,该方法将变量分配给XML文件中的元素。
*/
私有void赋值变量(){
//初始化xml文件中的变量。
btnStart=view.findviewbyd(R.id.checkInDailyButtonStart);
tvSetUpNotifications=view.findViewById(R.id.setUpNotificationsTextView);
cvNotification=view.findViewById(R.id.notification\u cardView2);
//配置顶部工具栏
mToolbar=view.findviewbyd(R.id.toolbar\u check\u in\u intro);
btnBack=mToolbar.findviewbyd(R.id.toolbar\u back\u按钮);
btnNext=mToolbar.findviewbyd(R.id.toolbar\u next\u按钮);
btnNext.hide();
tvTitle=mToolbar.findviewbyd(R.id.toolbar\u-workout\u-title);
tvTitle.setVisibility(View.VISIBLE);
setTextColor(ContextCompat.getColor(getActivity(),R.color.white));
setText(getString(R.string.check_in));
tvDescription=mToolbar.findViewById(R.id.toolbar\u-workout\u-description);
tvDescription.setVisibility(View.GONE);
tvDescription.setTextColor(ContextCompat.getColor(getContext(),R.color.white));
ivToolbar=mToolbar.findviewbyd(R.id.toolbar\u锻炼\u背景);
ivToolbar.setVisibility(View.VISIBLE);
ivToolbar.setImageResource(R.drawable.check_in_intro);
}
/**
*将onClickListeners设置为按钮的方法
*/
私有void setOnClickListeners(){
btnStart.setOnClickListener(此);
btnBack.setOnClickListener(这个);
tvSetUpNotifications.setOnClickListener(此);
cvNotification.setOnClickListener(此);
}
@凌驾
公共void onClick(视图){
开关(view.getId()){
案例R.id.工具栏\返回\按钮:
if(mNavController.getCurrentDestination().getId()==R.id.workoutCheckInIntro){
mNavController.导航(R.id.action\u workoutCheckInIntro\u至\u workoutFragment);
}
打破
案例R.id.checkInDailyButtonStart:
//在workoutcheckindailmod.Class中使用布尔值,因此当用户单击
//单击“上一步”按钮,它将使他们返回此活动。
args.putBoolean(训练\签入\每日\情绪,真);
if(mNavController.getCurrentDestination().getId()==R.id.workoutCheckInIntro){
mNavController.导航(R.id.action\u workoutCheckInIntro\u到\u workoutMood,args);
}
打破
案例R.id.notification_cardView2:
//NotificationsSetUp.Class中使用的布尔值,因此当用户单击
//单击“上一步”按钮,它将使他们返回此活动。
args.putBoolean(返回到CHECKIN训练,true);
if(mNavController.getCurrentDestination().getId()==R.id.workoutCheckInIntro){
mNavController.导航(R.id.action\u workoutCheckInIntro\u to\u notifications安装程序,args);
}
打破
}
}
@凌驾
公共无效onDestroyView(){
super.onDestroyView();
mToolbar=null;
视图=空;
btnBack=null;
btnNext=null;
tvDescription=null;
tvTitle=null;
ivToolbar=null;
btnStart=null;
cvNotification=null;
tvSetUpNotifications=null;
}
}
───
│ GC根:系统类
│
├─ android.provider.FontsContract类
│ 泄漏:否(基本应用程序↓ 不泄漏,类从不泄漏)
│ ↓ 静态FontsContract.sContext
├─ com.example.BaseApplication实例
│