Skip to content

Instantly share code, notes, and snippets.

View shikto1's full-sized avatar

Ahidul Islam shikto1

View GitHub Profile
OkHttpClient okHttpClient = new OkHttpClient.Builder()
// .addInterceptor(provideHttpLoggingInterceptor()) // For HTTP request & Response data logging
.addInterceptor(OFFLINE_INTERCEPTOR)
.addNetworkInterceptor(ONLINE_INTERCEPTOR)
.cache(cache)
.build();
val cacheSize = (10 x 1024 x 1024).toLong() // 10 MB
val cache = Cache(context.cacheDir, cacheSize)
static Interceptor offlineInterceptor= new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!isInternetAvailable()) {
int maxStale = 60 * 60 * 24 * 30; // Offline cache available for 30 days
request = request.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.removeHeader("Pragma")
.build();
static Interceptor onlineInterceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response response = chain.proceed(chain.request());
int maxAge = 60; // read from cache for 60 seconds even if there is internet connection
return response.newBuilder()
.header("Cache-Control", "public, max-age=" + maxAge)
.removeHeader("Pragma")
.build();
}
public class StaticReferenceLeakActivity extends AppCompatActivity {
/*
* This is a bad idea!
*/
private static TextView textView;
private static Activity activity;
@Override
public class SingletonSampleClass {
private Context mContext;
private static SingletonSampleClass instance = null;
private SingletonSampleClass(Context context) {
this.mContext = mContext;
}
public class GoodActivity extends AppCompatActivity {
private BroadcastReceiver mBroadcastReceiver;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
mBroadcastReceiver = new BroadcastReceiver() {
public class LeaksActivity extends AppCompatActivity {
private BroadcastReceiver mBroadcastReceiver;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
public class SingletonManager {
private static SingletonManager mManager = null;
public synchronized static SingletonManager getInstance(Context context) {
if (mManager == null) {
// Here i am using application context to avoid memory leak...
mManager = new SingletonManager(context.getApplicationContext());
}
public class SingletonActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
//...
SingletonManager.getInstance(getApplicationContext());
}
}