Automation/app/src/main/java/eu/chainfire/libsuperuser/Application.java

88 lines
2.7 KiB
Java
Raw Normal View History

2021-02-16 13:42:49 +01:00
/*
2021-05-18 20:02:45 +02:00
* Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma
2021-02-16 13:42:49 +01:00
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.chainfire.libsuperuser;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
2021-05-18 20:02:45 +02:00
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
2021-02-16 13:42:49 +01:00
/**
* Base application class to extend from, solving some issues with
* toasts and AsyncTasks you are likely to run into
*/
2021-05-18 20:02:45 +02:00
@SuppressWarnings("WeakerAccess")
2021-02-16 13:42:49 +01:00
public class Application extends android.app.Application {
/**
* Shows a toast message
2021-05-18 20:02:45 +02:00
*
2021-02-16 13:42:49 +01:00
* @param context Any context belonging to this application
* @param message The message to show
*/
2021-05-18 20:02:45 +02:00
@AnyThread
public static void toast(@Nullable Context context, @NonNull String message) {
2021-02-16 13:42:49 +01:00
// this is a static method so it is easier to call,
// as the context checking and casting is done for you
if (context == null) return;
if (!(context instanceof Application)) {
context = context.getApplicationContext();
}
if (context instanceof Application) {
final Context c = context;
final String m = message;
2021-05-18 20:02:45 +02:00
((Application) context).runInApplicationThread(new Runnable() {
2021-02-16 13:42:49 +01:00
@Override
public void run() {
Toast.makeText(c, m, Toast.LENGTH_LONG).show();
}
});
}
}
2021-05-18 20:02:45 +02:00
private static final Handler mApplicationHandler = new Handler();
2021-02-16 13:42:49 +01:00
/**
* Run a runnable in the main application thread
2021-05-18 20:02:45 +02:00
*
2021-02-16 13:42:49 +01:00
* @param r Runnable to run
*/
2021-05-18 20:02:45 +02:00
@AnyThread
public void runInApplicationThread(@NonNull Runnable r) {
2021-02-16 13:42:49 +01:00
mApplicationHandler.post(r);
}
@Override
public void onCreate() {
super.onCreate();
try {
// workaround bug in AsyncTask, can show up (for example) when you toast from a service
// this makes sure AsyncTask's internal handler is created from the right (main) thread
Class.forName("android.os.AsyncTask");
} catch (ClassNotFoundException e) {
// will never happen
}
}
}