(AsyncTask) Open a dialog when catch (Jsoup) - java

I want the dialog to open when "AsyncTask" is "catch". I tried to call Dialogue into a “catch”. But the program is crashing. How do I open a dialog when there is a catch?
My code:
public class test extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = (Document) Jsoup.connect("(warn: here my web)").get();
test = doc.text();
} catch (Exception e)
//Here problem dialog open. App crash
OpenDialog();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
Toast.makeText(MainActivity.this, test, Toast.LENGTH_LONG).show();
}
}
logcat error (red):
2021-12-17 07:22:10.953 17530-17564/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process, PID: 17530
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:415)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #1,5,main] that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:227)
at android.os.Handler.<init>(Handler.java:129)
at android.view.ViewRootImpl$ViewRootHandler.<init>(ViewRootImpl.java:5041)
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:5369)
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:763)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:399)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:111)
at android.app.Dialog.show(Dialog.java:342)
at Main.qaytaDialog(Main.java:130)
at Main.access$000(Main.java:24)
at Main$dooit.doInBackground(Main.java:95)
at Main$dooit.doInBackground(Main.java:83)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:923) 

A bit broad but here are some tips. Displaying dialogs is foreground thing (runs on main or UI thread) so it can not be done in background method of async task (it runs on background Thread).It is only allowed from methods such as onPostExecute(), onPublishProgress().
Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread[AsyncTask #1,5,main] that has not called Looper.prepare()
Please refer to this link for details
Here is a quick code snippet for your reference
public class MyAsync extends AsyncTask<Void, Void, Void> {
Boolean isCatched=false;
#Override
protected Void doInBackground(Void... voids) {
try {
if (!isCatched)
throw new Exception();
Log.i("Test", "doInBackground: ");
} catch (Exception e){
//Here problem dialog open. App crash
isCatched=true;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
if (isCatched)
OpenDialog();
Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_LONG).show();
}
}

Related

ANdroid lang runtime exception error, how to resolve it?

I am getting the following error in my android studio. Is there any way I can solve this issue. Its causing a lot of crashes in my app.
E/AndroidRuntime: FATAL EXCEPTION: Firebase-Messaging-Intent-Handle
Process: com.cnlcabs.cnldrivers, PID: 19224
java.lang.RuntimeException: Can't create handler inside thread Thread[Firebase-Messaging-Intent-Handle,5,main] that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:227)
at android.os.Handler.<init>(Handler.java:129)
at com.cnlcabs.cnldrivers.data.MyFirebaseMessagingService.stopPlayer(MyFirebaseMessagingService.java:264)
at com.cnlcabs.cnldrivers.data.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:233)
at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(com.google.firebase:firebase-messaging##21.1.0:13)
at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(com.google.firebase:firebase-messaging##21.1.0:8)
at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(com.google.firebase:firebase-messaging##21.1.0:3)
at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(com.google.firebase:firebase-messaging##21.1.0:3)
at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(com.google.firebase:firebase-messaging##21.1.0:1)
at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(Unknown Source:6)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at com.google.android.gms.common.util.concurrent.zza.run(com.google.android.gms:play-services-basement##17.5.0:6)
at java.lang.Thread.run(Thread.java:923)
my code for myfirebasemessagingservice line 264 is
private void stopPlayer() {
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (NotificationReceiverSoundPlay.mPlayer != null)
NotificationReceiverSoundPlay.mPlayer.stop();
}
}, 2000);
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
You need to run these lines in UI thread not in a separate thread. Like this answer.
new Handler().postDelayed(new Runnable() {
activity.runOnUiThread(new Runnable() {
public void run() {
if (NotificationReceiverSoundPlay.mPlayer != null)
NotificationReceiverSoundPlay.mPlayer.stop();
}
});
}, 2000);

Android- java.lang.IllegalArgumentException

I already have seen this question. But couldn't figure out what's the issue.
I am sending an email in background using BackgroundMail in my ImageSyncReciever class. But when email is sent my app crashes while giving me the below error
FATAL EXCEPTION: main
Process: com.thumbsol.accuratemobileassetsmanagament, PID: 7480
java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{300e55de V.E..... R.....I. 0,0-0,0} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:434)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:353)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116)
at android.app.Dialog.dismissDialog(Dialog.java:382)
at android.app.Dialog.dismiss(Dialog.java:365)
at com.creativityapps.gmailbackgroundlibrary.BackgroundMail$SendEmailTask.onPostExecute(BackgroundMail.java:302)
at com.creativityapps.gmailbackgroundlibrary.BackgroundMail$SendEmailTask.onPostExecute(BackgroundMail.java:265)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5660)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:963)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)
Below is my code in which I am sending the email
if (response.body().getStatus().equals("OK")) {
snapManager.updateSnapStatus(AssetsManagementContract.SnapEntry.COLUMN_SITE_SNAP, snap.getSnapName(), Constants.SNAP_SYNCED);
Intent broadcastSyc = new Intent();
broadcastSyc.setAction(Common.GetSyncImageAction());
broadcastSyc.putExtra("STATUS", true);
mContext.sendBroadcast(broadcastSyc);
sendImage(mContext);
BackgroundMail.newBuilder(mContext)
.withUsername("gmail id")
.withPassword("pass")
.withMailto("gmail id")
.withType(BackgroundMail.TYPE_PLAIN)
.withSubject("New Meter Installation")
.withBody("Meter #" + msn + " is "+ com+ " and "+ status)
.send();
}
How can i resolve this issue? Any help would be highly appreciated
Note: The email is sent when the form is submitted and after saving I am not using any dialog.
Update 1
Below is the BackgroudMailer class function
public class SendEmailTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progressDialog;
public SendEmailTask() { //error onPostExecute(BackgroundMail.java:265)
}
protected void onPreExecute() {
super.onPreExecute();
if(BackgroundMail.this.processVisibility) {
this.progressDialog = new ProgressDialog(BackgroundMail.this.mContext);
this.progressDialog.setMessage(BackgroundMail.this.sendingMessage);
this.progressDialog.setCancelable(false);
this.progressDialog.show();
}
}
protected Boolean doInBackground(String... arg0) {
try {
GmailSender sender = new GmailSender(BackgroundMail.this.username, BackgroundMail.this.password);
if(!BackgroundMail.this.attachments.isEmpty()) {
for(int i = 0; i < BackgroundMail.this.attachments.size(); ++i) {
if(!((String)BackgroundMail.this.attachments.get(i)).isEmpty()) {
sender.addAttachment((String)BackgroundMail.this.attachments.get(i));
}
}
}
sender.sendMail(BackgroundMail.this.subject, BackgroundMail.this.body, BackgroundMail.this.username, BackgroundMail.this.mailto, BackgroundMail.this.type);
} catch (Exception var4) {
var4.printStackTrace();
return Boolean.valueOf(false);
}
return Boolean.valueOf(true);
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(BackgroundMail.this.processVisibility) {
this.progressDialog.dismiss(); // error onPostExecute(BackgroundMail.java:302)
if(result.booleanValue()) {
if(!TextUtils.isEmpty(BackgroundMail.this.sendingMessageSuccess)) {
Toast.makeText(BackgroundMail.this.mContext, BackgroundMail.this.sendingMessageSuccess, 0).show();
}
if(BackgroundMail.this.onSuccessCallback != null) {
BackgroundMail.this.onSuccessCallback.onSuccess();
}
} else {
if(!TextUtils.isEmpty(BackgroundMail.this.sendingMessageError)) {
Toast.makeText(BackgroundMail.this.mContext, BackgroundMail.this.sendingMessageError, 0).show();
}
if(BackgroundMail.this.onFailCallback != null) {
BackgroundMail.this.onFailCallback.onFail();
}
}
}
}
}
The problem is I cannot edit it as the file is locked.
in onPostExecute you dismiss the dialog without checking if it is actually shown:
this.progressDialog.dismiss();
add a check of isShowing for that (and a null-check just in case..)
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
Also I see that you use static references to contexts. That can lead to memory leaks, but that is just a side note.

Android - java.lang.RuntimeException: Could not read input channel file descriptors from parcel

I'm getting a FATAL EXCEPTION: main when I run the app. It run first but for a few seconds it crash.
Here is my Logcat :
java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
at android.view.InputChannel.nativeReadFromParcel(Native Method)
at android.view.InputChannel.readFromParcel(InputChannel.java:148)
at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:752)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:527)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at android.app.AlertDialog$Builder.show(AlertDialog.java:993)
at com.mobext.shakeys.ActivityMain$ProcessData.onPostExecute(ActivityMain.java:545)
at com.mobext.shakeys.ActivityMain$ProcessData.onPostExecute(ActivityMain.java:212)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Inside my ActivityMain.java:542 in alrt.show() this is where the logcat point it:
#Override
protected void onPostExecute(Boolean result) {
Log.i(TAG, "onPostExecute");
super.onPostExecute(result);
if(result){
Log.i(TAG, "TASK IS DONE");
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
app.saveToLastPref(ActivityMain.this, app.PREFS_PREV_VERSION, pInfo.versionName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), ActivityMenuPage.class);
startActivity(intent);
finish();
}else{
ActivityMain.this.deleteDatabase("DBSHAKEYS");
Builder alrt = new AlertDialog.Builder(mcontext);
alrt.setMessage("Update failed. Please check your internet connection and try again.");
alrt.setPositiveButton("Okay", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alrt.show();
}
}
}
And in ActivityMain.java:212 :
public class ProcessData extends AsyncTask<Void, Void, Boolean>
I think Builder is your custom class that you are using now to show the AlertDialog.
Here is what may happened
The onPostExecute() method was called automatically after your some background process was finished executing. And then It tried to use the Builder class which may be currently being used by another process and still running in the memory.
How can it be solved then ?
Review your code and see if the dialog is already being shown using
Builder class.
Simply change this line
Builder alrt = new AlertDialog.Builder(mcontext); to normally AlertDialog.Builder alrt = new AlertDialog.Builder(mcontext);
and see if this works.

Async Task FTP Upload Android Service Crashing?

I am trying to upload via FTP a file in a set directory. The file is called "advancedsettings.xml".
The code works fine when used in the Async Task of an Activity, but when attempting to use a Service to carry out the exact same operations within an Async Task, the application crashes with the following error(s):
01-13 16:21:08.403 21134-21151/com.name.example.xx E/AndroidRuntime﹕
FATAL EXCEPTION: AsyncTask #1 Process: com.name.example.xx, PID: 21134
java.lang.RuntimeException: An error occured while executing
doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at
java.util.concurrent.FutureTask.finishCompletion(F utureTask.java:355)
at java.util.concurrent.FutureTask.setException(Futur eTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.jav a:242) at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTas k.java:231) at
java.util.concurrent.ThreadPoolExecutor.runWorker(
ThreadPoolExecutor.java:1112) at
java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside
thread that has not called Looper.prepare() at
android.os.Handler.(Handler.java:200) at
android.os.Handler.(Handler.java:114) at
android.widget.Toast$TN.(Toast.java:388) at
android.widget.Toast.(Toast.java:114) at
android.widget.Toast.makeText(Toast.java:273) at
com.name.example.xx.MyService$FTPUpload.doInBackgr
ound(MyService.java:58) at
com.name.example.xx.MyService$FTPUpload.doInBackgr
ound(MyService.java:55) at
android.os.AsyncTask$2.call(AsyncTask.java:288) at
java.util.concurrent.FutureTask.run(FutureTask.jav a:237)
************at android.os.AsyncTask$SerialExecutor$1.run(AsyncTas k.java:231)
************at java.util.concurrent.ThreadPoolExecutor.runWorker( ThreadPoolExecutor.java:1112)
************at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:587)
************at java.lang.Thread.run(Thread.java:841) 01-13 16:21:08.473 862-862/? W/ContextImpl﹕ Calling a method in the system
process without a qualified user:
android.app.ContextImpl.sendBroadcast:1505
com.android.server.analytics.data.collection.appli
cation.CrashAnrDetector.broadcastEvent:296
com.android.server.analytics.data.collection.appli
cation.CrashAnrDetector.processDropBoxEntry:254
com.android.server.analytics.data.collection.appli
cation.CrashAnrDetector.access$100:60
com.android.server.analytics.data.collection.appli
cation.CrashAnrDetector$1.onReceive:102 01-13 16:21:08.713 862-21154/?
E/android.os.Debug﹕ !#Dumpstate > sdumpstate -k -t -z -d -o
/data/log/dumpstate_app_error
Here is how I call the service from within my main activity (on button click):
Intent inetnt=new Intent(FileChooser.this, MyService.class);
startService(inetnt);
And here is the Service code:
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(MyService.this, "service start", Toast.LENGTH_LONG).show();
new FTPUpload().execute();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public class FTPUpload extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void...params) {
Toast.makeText(MyService.this, "Service FTP Upload Start", Toast.LENGTH_LONG).show();
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("host");
// Check your USERNAME e.g myuser#mywebspace.com and check your PASSWORD to ensure they are OK.
if (con.login("username", "password")) {
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
Random rand = new Random();
String randomIntString = String.valueOf(rand.nextInt()).replaceAll("-", "");
FileInputStream in = new FileInputStream("/storage/emulated/0/");
//con.makeDirectory("/" + randomIntString + "/");
con.storeFile("advancedsettings.xml", in);
in.close();
//PASS URL TO NEXT ACTIVITY AND LAUNCH NEXT ACTIVITY ON NOTIFICATION CLICK
} else {
}
} catch (
Exception e
)
{ //if file does not upload successfully, write an error log.
Toast.makeText(MyService.this, "An error occured, please report: " + e, Toast.LENGTH_LONG).show();
}
Toast.makeText(MyService.this, "Service FTP Upload Complete", Toast.LENGTH_LONG).show();
return null;
}
}
}
I can confirm I have declared the service in my Android Manifest file within the application tag, as follows:
<service android:name=".MyService"/>
Any ideas guys? Thank you so much in advance for your help! I'm so keen to get to the bottom of this.
K
Please do not access the main thread from doInBackground, like running a Toast. Use onPreExecute for this kind of opperation instead.
Toast.makeText(MyService.this,
"Service FTP Upload Start",
Toast.LENGTH_LONG).show();
doInBackground should/can not access the UI Thread. For your complete task Toasts try to return a value from doInBackground, you will get the returned value in onPostExecute where you can show your toasts
For further Information have a look at the Documentation:
Documentation
Here
Toast.makeText(MyService.this, "Service FTP Upload Start", Toast.LENGTH_LONG).show();
You are trying to so Toast from doInBackground (from other Thread). use onPreExecute to show Toast before starting doInBackground execution

android.view.WindowLeaked for tablet asynctask while trying to set portrait orientation

I have an activity that is displayed in portrait only and in my tablet it causes the following:
android.view.WindowLeaked: Activity com.spicycurryman.getdisciplined10.app.InstalledAppActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{53210b88 V.E..... R.....ID 0,0-1520,192} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.spicycurryman.getdisciplined10.app.InstalledAppActivity$LoadApplications.onPreExecute(InstalledAppActivity.java:306)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.spicycurryman.getdisciplined10.app.InstalledAppActivity.onCreate(InstalledAppActivity.java:105)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I am using an AsyncTask to load a listview of installed apps on the phone and using a progressdialog.
I have researched this problem:
Progress dialog and AsyncTask error
android.view.WindowLeaked exception
Android Error: Window Leaked in AsyncTask
I was able to produce this code so that the whole app doesn't crash and burn, but the exception is still thrown and the activity screen is kind of shaky after the button click and the whole transition is not really smooth.
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(InstalledAppActivity.this, packageList1, packageManager));
try {
if ((this.pDialog != null) && this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.pDialog = null;
}
super.onPostExecute(result);
}
Dismissing the progress dialog or calling finish() doesn't really solve the problem either...
How would I fix this?
Here is most of the AsyncTask code:
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
List<PackageInfo> packageList2 = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
boolean d = isSystemPackage2(pi);
if ((!b || !c ) && d ){
packageList1.add(pi);
}
}
//here you got email and message apps in the
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage3(pi);
boolean c = isSystemPackage4(pi);
if (b || c){
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this);
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
//Inefficient patch to prevent Window Manager error
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(InstalledAppActivity.this, packageList1, packageManager));
try {
if ((this.pDialog != null) && this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.pDialog = null;
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
try this :
#Override
public Object onRetainNonConfigurationInstance() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog = null;
}
if (asynTask!= null) {
asynTask.detach();
}
return ayncTask;
}
Declaring a non-static inner AsyncTask in your activity is not a good idea because it holds a reference to the activity and this could be a couse of the leak. However, various configuration changes could cause the OS to destroy and recreate the activity. There are a number of solutions and Rustam's anser is an example.
However, I prefer to user either AsyncTaskLoader or use some sort of asynchronous callback, like a broadcast. The asynchronous callback decouples your AsyncTask from the Activity.

Categories