refactor: use GlobalAppContext to replace App.getApp()

add: Canvas
This commit is contained in:
hyb1996
2018-03-23 14:45:48 +08:00
parent d098c77827
commit a009eb02b0
33 changed files with 666 additions and 117 deletions

View File

@@ -0,0 +1,77 @@
package com.stardust.app;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.RequiresApi;
import android.widget.Toast;
/**
* Created by Stardust on 2018/3/22.
*/
public class GlobalAppContext {
@SuppressLint("StaticFieldLeak")
private static Context sApplicationContext;
private static Handler sHandler;
public static void set(Application a) {
if (sApplicationContext != null)
throw new IllegalStateException();
sHandler = new Handler(Looper.getMainLooper());
sApplicationContext = a.getApplicationContext();
}
public static Context get() {
if (sApplicationContext == null)
throw new IllegalStateException("Call GlobalAppContext.set() to set a application context");
return sApplicationContext;
}
public static String getString(int resId) {
return get().getString(resId);
}
public static String getString(int resId, Object... formatArgs) {
return get().getString(resId, formatArgs);
}
@RequiresApi(api = Build.VERSION_CODES.M)
public static int getColor(int id) {
return get().getColor(id);
}
public static void toast(final String message) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Toast.makeText(get(), message, Toast.LENGTH_SHORT).show();
return;
}
sHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(get(), message, Toast.LENGTH_SHORT).show();
}
});
}
public static void toast(final int resId) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Toast.makeText(get(), resId, Toast.LENGTH_SHORT).show();
return;
}
sHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(get(), resId, Toast.LENGTH_SHORT).show();
}
});
}
public static void post(Runnable r) {
sHandler.post(r);
}
}