Andorid自定义Application(可继承,可自定义各种参数和配置)

想法是,所有项目的application都能继承这个某一个作为父类,但该不同的东西,可自行设定,直接上代码

public abstract class BaseApp extends Application {
    /**
     * 版本
     */
    public static final double VERSION = 2.8;
    public static ApplicationOptions options;
    private static Application app;
    private static final List< Activity > ACTIVITY_LIST = new ArrayList<> ( );
    public static int width = 1080;
    public static int height = 1920;
    public static float density = 0;
    public static String PackageName;
    public volatile static boolean isWifi = false;

    @Override
    public void onCreate ( ) {
        super.onCreate ( );
        app = this;
        PackageName = getContext ( ).getPackageName ( );
        ShareUtils.init ( app );
        registerActivityLifecycleCallbacks ( activityLifecycleCallbacks );
        //设置时区
//        TimeZone.setDefault ( TimeZone.getTimeZone ( "UTC" ) );
        TimeZone.setDefault ( TimeZone.getTimeZone ( "GMT+08" ) );
        registerNetworkCallback ( this );
        options = setOptions ( );
        Logger.init ( options.logTag, options.isDebug );
        initSize ( options.vertical );
    }

    @SuppressLint ( "MissingPermission" )
    public static void shake ( long milliseconds ) {
        Vibrator vib =
                ( Vibrator ) getContext ( ).getSystemService ( Service.VIBRATOR_SERVICE );
        if ( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ) {
            vib.vibrate ( VibrationEffect.createOneShot ( milliseconds, 105 ) );
        } else {
            vib.vibrate ( milliseconds );
        }
    }

    @SuppressLint ( "MissingPermission" )
    public static void shake ( ) {
        shake ( 100 );
    }

    /**
     * 设置属性
     *
     * @return ApplicationOptions
     */
    protected abstract ApplicationOptions setOptions ( );


    @SuppressWarnings ( "SuspiciousNameCombination" )
    private void initSize ( boolean vertical ) {
        DisplayMetrics dm = getContext ( ).getResources ( ).getDisplayMetrics ( );
        if ( vertical ) {
            if ( dm.widthPixels > dm.heightPixels ) {
                BaseApp.width = dm.heightPixels;
                BaseApp.height = dm.widthPixels;
            } else {
                BaseApp.width = dm.widthPixels;
                BaseApp.height = dm.heightPixels;
            }
        } else {
            if ( dm.widthPixels < dm.heightPixels ) {
                BaseApp.width = dm.heightPixels;
                BaseApp.height = dm.widthPixels;
            } else {
                BaseApp.width = dm.widthPixels;
                BaseApp.height = dm.heightPixels;
            }
        }
        BaseApp.density = dm.density;

        Logger.i ( "分辨率:" + width + "*" + height + ",像素密度1:" + dm.density + ",像素密度2:" + dm.densityDpi );
    }

    public static Application getApp ( ) {
        return app;
    }

    public static String getPackName ( ) {
        return getApp ( ).getPackageName ( );
    }

    public static Context getContext ( ) {
        return app.getApplicationContext ( );
    }


    private final Application.ActivityLifecycleCallbacks activityLifecycleCallbacks =
            new Application.ActivityLifecycleCallbacks ( ) {
                @Override
                public void onActivityCreated ( @NonNull Activity activity,
                                                @Nullable Bundle savedInstanceState ) {
                    ACTIVITY_LIST.add ( activity );
                }

                @Override
                public void onActivityStarted ( @NonNull Activity activity ) {

                }

                @Override
                public void onActivityResumed ( @NonNull Activity activity ) {

                }

                @Override
                public void onActivityPaused ( @NonNull Activity activity ) {

                }

                @Override
                public void onActivityStopped ( @NonNull Activity activity ) {

                }

                @Override
                public void onActivitySaveInstanceState ( @NonNull Activity activity,
                                                          @NonNull Bundle outState ) {

                }

                @Override
                public void onActivityDestroyed ( @NonNull Activity activity ) {
                    ACTIVITY_LIST.remove ( activity );
                }
            };

    public static Activity getTopActivity ( ) {
        return ACTIVITY_LIST.get ( ACTIVITY_LIST.size ( ) - 1 );
    }

    public static void exit ( ) {
        for ( Activity a : ACTIVITY_LIST ) {
            a.finish ( );
        }
    }

    public static void exit ( Activity activity, Class< ? > mClass ) {
        for ( Activity a : ACTIVITY_LIST ) {
            if ( ! a.getClass ( ).getSimpleName ( ).equals ( activity.getClass ( ).getSimpleName ( ) ) ) {
                a.finish ( );
            }
        }
        activity.startActivity ( new Intent ( activity, mClass ) );
        activity.finish ( );
    }

    public static void finishButMain ( ) {
        for ( Activity a : ACTIVITY_LIST ) {
            String current = a.getClass ( ).getSimpleName ( );
            if ( ! current.contains ( "MainActivity" ) ) {
                a.finish ( );
            }
        }
    }

    @SuppressLint ( "MissingPermission" )
    private static void registerNetworkCallback ( Context context ) {
        try {
            isWifi = NetWorkUtils.isWifi ( );
            ConnectivityManager cm =
                    ( ConnectivityManager ) context.getSystemService ( Context.CONNECTIVITY_SERVICE );
            NetworkRequest.Builder builder = new NetworkRequest.Builder ( );
            builder.addTransportType ( NetworkCapabilities.TRANSPORT_WIFI );
            builder.addTransportType ( NetworkCapabilities.TRANSPORT_CELLULAR );
            cm.registerNetworkCallback ( builder.build ( ), CALLBACK );
        } catch ( Exception e ) {
            e.printStackTrace ( );
        }
    }

    private final static ConnectivityManager.NetworkCallback CALLBACK =
            new ConnectivityManager.NetworkCallback ( ) {
                @Override
                public void onCapabilitiesChanged ( @NonNull Network network,
                                                    @NonNull NetworkCapabilities capabilities ) {
                    super.onCapabilitiesChanged ( network, capabilities );

                    fresh ( );
                }

                @Override
                public void onLost ( @NonNull Network network ) {
                    super.onLost ( network );
                    fresh ( );
                }

                @Override
                public void onAvailable ( @NonNull Network network ) {
                    super.onAvailable ( network );
                    fresh ( );
                }

                private synchronized void fresh ( ) {
                    boolean b = NetWorkUtils.isWifi ( );
                    if ( b != isWifi ) {
                        isWifi = b;
                        ListenerManager.callActionBack ( ActionType.NET_WORK_CHANGE_CODE, b ?
                                "1" : "0" );
                    }
                }
            };
}

使用方法

public class LuckApp extends BaseApp {
    @Override
    public void onCreate ( ) {
        super.onCreate ( );
        LitePal.initialize ( this );
        if ( BuildConfig.DEBUG ) {
            SQLiteStudioService.instance ( ).start ( getContext ( ) );
        }
    }

    @Override
    protected ApplicationOptions setOptions ( ) {
        return ApplicationOptions.create ( )
                .setMainColorByRes ( R.color.main )
                .setDebug ( BuildConfig.DEBUG )
                .setLogTag ( "Luck" )
                ;
    }
}

你可能感兴趣的:(Andorid自定义Application(可继承,可自定义各种参数和配置))