Android Asyntask: Use weak reference for context to avoid device rotate screen

Somewhere in your AsyncTask you’ll want to pass in your activity. Then you’ll save that reference in a weak reference. Then you can dereference and use it again in onPostExecute. Class member: WeakReference<Activity> weakActivity; Somewhere in AsyncTask, probably either constructor or onPreExecute: weakActivity = new WeakReference<Activity>(activity); In onPostExecute: Activity activity = weakActivity.get(); if (activity != … Read more

How to start an Intent if context is not Activity Context but Application Context

Here is sample code how to call another activity using context, set flag as per your requirement: public void onReceive(Context context, Intent intent) { Intent intent = new Intent(); intent.setClass(context, xxx.class); intent.setAction(xxx.class.getName()); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); context.startActivity(intent); }

Android: why must use getBaseContext() instead of this

getApplicationContext () returns the application context of the entire application life cycle,when application will destroy then it will destroy also. this the context returns the current context of the activity, belong to the activity, the activity is destroyed then it will destroy also.but in your case it will refers to the Spinner instance because we … Read more

Difference between getContext() and requireContext() when using fragments

getContext() returns a nullable Context. requireContext() returns a nonnull Context, or throws an exception when one isn’t available. If your code is in a lifecycle phase where you know your fragment is attached to a context, just use requireContext() to get a Context and also keep static analyzers happy about potential NPE issues. If your … Read more

Diffinitive rules for using Android’s getBaseContext, getApplicationContext or using an Activity’s “this”

The getBaseContext() is the method of ContextWrapper. And ContextWrapper is, “Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.” (as per javadocs) So this is used to delegate the calls to another context.

Android 13 (SDK 33): PackageManager.getPackageInfo(String, int) deprecated. what is the alternative?

If you are using Kotlin, you can add extension function to your project: fun PackageManager.getPackageInfoCompat(packageName: String, flags: Int = 0): PackageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags.toLong())) } else { @Suppress(“DEPRECATION”) getPackageInfo(packageName, flags) } and after just call packageManager.getPackageInfoCompat(packageName) or add another flag, if you need.