泄漏金丝雀通知没有显示。

时间:2017-08-30 02:28:10

标签: android memory-leaks

 package injection.view.mainactivity;

     import android.content.Context;
     import android.content.Intent;
     import android.os.AsyncTask;
     import android.support.v7.app.AppCompatActivity;
     import android.os.Bundle;
     import android.util.Log;
     import com.squareup.leakcanary.RefWatcher;
     import javax.inject.Inject;

     import injection.mainactivity.DaggerMainActivityComponent;
     import injection.mainactivity.ExampleApplication;
     import injection.mainactivity.MainActivityComponent;
     import injection.view.AnotherActivity.AnotherActivity;
     import webv.agoel.mvpdagger.R;

     public class MainActivity extends AppCompatActivity implements 
      MainActivityContract.View {


private static final String TAG = "MainActivity";
@Inject
MainActivityPresenter presenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DaggerMainActivityComponent.create().inject(this);
    presenter.addView(this);
    presenter.doCalculation("hello world");
    new MyAsyncTask().execute(this);
}

@Override
public void onDestroy() {
    super.onDestroy();
    RefWatcher refWatcher = ExampleApplication.getRefWatcher(this);
    refWatcher.watch(this);
}

@Override
public void updateView(String log) {
    Log.d(TAG, "updateView: " + log);
}

public class MyAsyncTask extends AsyncTask<Object, String, String> {
    private Context context;

    @Override
    protected String doInBackground(Object... params) {
        context = (Context) params[0];

        // Invoke the leak!
        SingletonSavesContext.getInstance().setContext(context);


        return "result";
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        Intent newActivity = new Intent(context, AnotherActivity.class);
        startActivity(newActivity);
    }
}

}

为什么上面的代码没有在我的设备上显示泄漏金丝雀通知?

我做了以下步骤

1。)创建将保留上下文的Singleton(Activity) 2.)将主活动的上下文设置为Singleton。 3.)启动AnotherActivity导致内存泄漏。

但是,我没有看到任何泄漏金丝雀通知。

1 个答案:

答案 0 :(得分:0)

试试吧!

public class MyAsyncTask extends AsyncTask<Object, String, String> {
private WeakReference<MainActivity> mWeakReference;

public GetDataAsync(MainActivity activity) {
        mWeakReference = new WeakReference<>(activity);
    }
@Override
protected String doInBackground(Object... params) {
    MainActivity activity = mWeakReference.get();
    // Invoke the leak!
    SingletonSavesContext.getInstance().setContext(activity);


    return "result";
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    MainActivity activity = mWeakReference.get();
    Intent newActivity = new Intent(activity, AnotherActivity.class);
    activity.startActivity(newActivity);
}
}

在Oncreate()

new MyAsyncTask(this).execute();