Java Code Examples for android.app.Application

The following are top voted examples for showing how to use android.app.Application. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: android-apkbox   File: ApkHook.java   View source code 6 votes vote down vote up
/**
 * hookPackageManager
 *
 * @param application application
 */
private static void hookPackageManager(Application application) {
    try {
        Object currentActivityThread = HookCurrentActivityThread.getCurrentActivityThread(application);
        if (currentActivityThread != null) {
            Field sPackageManagerField = currentActivityThread.getClass().getDeclaredField("sPackageManager");
            sPackageManagerField.setAccessible(true);
            Object sPackageManager = sPackageManagerField.get(currentActivityThread);

            Class<?> iPackageManagerInterface = Class.forName("android.content.pm.IPackageManager");
            Object proxy = Proxy.newProxyInstance(iPackageManagerInterface.getClassLoader(),
                    new Class<?>[]{iPackageManagerInterface},
                    new HookPackageManagerHandler(sPackageManager));

            sPackageManagerField.set(currentActivityThread, proxy);

            PackageManager pm = application.getPackageManager();
            Field mPmField = pm.getClass().getDeclaredField("mPM");
            mPmField.setAccessible(true);
            mPmField.set(pm, proxy);
        }
    } catch (Exception e) {
        ApkLogger.get().debug("hookPackageManager Exception", e);
    }
}
 
Example 2
Project: MiPushFramework   File: CondomProcessTest.java   View source code 6 votes vote down vote up
@BeforeClass public static void checkInstallation() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException {
	try {
		CondomProcess.installExcept(((Application) InstrumentationRegistry.getTargetContext().getApplicationContext()),
				new CondomOptions().addKit(new NullDeviceIdKit()), "");
		fail("CondomKit is incompatible with CondomProcess");
	} catch (final IllegalArgumentException ignored) {}

	// Install in default process intentionally, since test cases cannot run in secondary process.
	CondomProcess.installExcept(((Application) InstrumentationRegistry.getTargetContext().getApplicationContext()), new CondomOptions(), "");

	// Check IActivityManager proxy
	@SuppressLint("PrivateApi") final Object am_proxy = Class.forName("android.app.ActivityManagerNative").getMethod("getDefault").invoke(null);
	assertTrue(Proxy.isProxyClass(am_proxy.getClass()));
	sCondomProcessActivityManager = (CondomProcess.CondomProcessActivityManager) Proxy.getInvocationHandler(am_proxy);
	assertEquals(CondomProcess.CondomProcessActivityManager.class, sCondomProcessActivityManager.getClass());

	// Check IPackageManager proxy
	final PackageManager pm = context().getPackageManager();
	assertEquals("android.app.ApplicationPackageManager", pm.getClass().getName());
	final Field ApplicationPackageManager_mPm = pm.getClass().getDeclaredField("mPM");
	ApplicationPackageManager_mPm.setAccessible(true);
	final Object pm_proxy = ApplicationPackageManager_mPm.get(pm);
	assertTrue(Proxy.isProxyClass(pm_proxy.getClass()));
	sCondomProcessPackageManager = (CondomProcess.CondomProcessPackageManager) Proxy.getInvocationHandler(pm_proxy);
	assertEquals(CondomProcess.CondomProcessPackageManager.class, sCondomProcessPackageManager.getClass());
}
 
Example 3
Project: react-native-leancloud-sdk   File: RNPushNotificationPublisher.java   View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    try {
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        long currentTime = System.currentTimeMillis();

        Log.i(LOG_TAG, "NotificationPublisher: Prepare To Publish: " + id + ", Now Time: " + currentTime);

        Application applicationContext = (Application) context.getApplicationContext();

        new RNPushNotificationHelper(applicationContext)
                .sendToNotificationCentre(intent.getExtras());
    } catch (Exception e) {

    }
}
 
Example 4
Project: android-mobile-engage-sdk   File: InAppMessageHandlerProviderTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException {
    Application application = (Application) InstrumentationRegistry.getTargetContext().getApplicationContext();
    inAppMessageHandler = mock(InAppMessageHandler.class);

    MobileEngageConfig config = new MobileEngageConfig.Builder()
            .application(application)
            .credentials("14C19-A121F", "PaNkfOD90AVpYimMBuZopCpm8OWCrREu")
            .disableDefaultChannel()
            .enableExperimentalFeatures(MobileEngageFeature.IN_APP_MESSAGING)
            .setDefaultInAppMessageHandler(inAppMessageHandler)
            .build();

    Field configField = MobileEngage.class.getDeclaredField("config");
    configField.setAccessible(true);
    configField.set(null, config);

    provider = new InAppMessageHandlerProvider();
}
 
Example 5
Project: android-mobile-engage-sdk   File: RequestUtilsTest.java   View source code 6 votes vote down vote up
@Before
public void setup() {
    config = new MobileEngageConfig.Builder()
            .application((Application) InstrumentationRegistry.getTargetContext().getApplicationContext())
            .credentials(APPLICATION_CODE, APPLICATION_PASSWORD)
            .disableDefaultChannel()
            .build();

    debugConfig = new MobileEngageConfig.Builder()
            .application(ApplicationTestUtils.applicationDebug())
            .credentials(APPLICATION_CODE, APPLICATION_PASSWORD)
            .disableDefaultChannel()
            .build();

    releaseConfig = new MobileEngageConfig.Builder()
            .application(ApplicationTestUtils.applicationRelease())
            .credentials(APPLICATION_CODE, APPLICATION_PASSWORD)
            .disableDefaultChannel()
            .build();

    deviceInfo = new DeviceInfo(InstrumentationRegistry.getContext());
}
 
Example 6
Project: AppVisibilityDetector   File: AppVisibilityDetector.java   View source code 6 votes vote down vote up
public static boolean checkIsMainProcess(Application app) {
    ActivityManager activityManager = (ActivityManager) app.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> runningAppProcessInfoList = activityManager.getRunningAppProcesses();
    if (null == runningAppProcessInfoList) {
        return false;
    }

    String currProcessName = null;
    int currPid = android.os.Process.myPid();
    //find the process name
    for (RunningAppProcessInfo processInfo : runningAppProcessInfoList) {
        if (null != processInfo && processInfo.pid == currPid) {
            currProcessName = processInfo.processName;
        }
    }

    //is current process the main process
    if (!TextUtils.equals(currProcessName, app.getPackageName())) {
        return false;
    }

    return true;
}
 
Example 7
Project: GmArchMvvm   File: CrashUtils.java   View source code 6 votes vote down vote up
/**
 * initialization
 * <p>Need to add permission {@code <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>}</p>
 *
 * @param crashDir Crash file storage directory
 * @return {@code true}: Initialized successfully<br>{@code false}: initialization failed
 */
public static boolean init(Application application, final String crashDir) {
    if (mApplication == null)
        mApplication = new WeakReference<>(application);
    if (isSpace(crashDir)) {
        dir = null;
    } else {
        dir = crashDir.endsWith(FILE_SEP) ? dir : dir + FILE_SEP;
    }
    if (mInitialized)
        return true;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            && mApplication.get().getExternalCacheDir() != null) {
        defaultDir = mApplication.get().getExternalCacheDir() + FILE_SEP + "crash" + FILE_SEP;
    } else {
        defaultDir = mApplication.get().getCacheDir() + FILE_SEP + "crash" + FILE_SEP;
    }
    Thread.setDefaultUncaughtExceptionHandler(UNCAUGHT_EXCEPTION_HANDLER);
    return mInitialized = true;
}
 
Example 8
Project: com.ruuvi.station   File: Foreground.java   View source code 5 votes vote down vote up
public static Foreground get(Context ctx){
    if (instance == null) {
        Context appCtx = ctx.getApplicationContext();
        if (appCtx instanceof Application) {
            init((Application)appCtx);
        }
        throw new IllegalStateException(
                "Foreground is not initialised and " +
                        "cannot obtain the Application object");
    }
    return instance;
}
 
Example 9
Project: GitHub   File: PresenterManagerTest.java   View source code 5 votes vote down vote up
@Test public void getActivityScopeReturnsExistingOne() {
  Activity activity = Mockito.mock(Activity.class);
  Application application = Mockito.mock(Application.class);

  Mockito.when(activity.getApplication()).thenReturn(application);

  ActivityScopedCache scope1 =
      PresenterManager.getOrCreateActivityScopedCache(activity);
  Assert.assertNotNull(scope1);
  Assert.assertEquals(scope1, PresenterManager.getActivityScope(activity));
}
 
Example 10
Project: FTC2016   File: Util.java   View source code 5 votes vote down vote up
/**
 * Gets the contexts of an activity without calling from an Activity class
 *
 * @return the main Application (as a Context)
 */
public static Context getContext() {
    try {
        final Class<?> activityThreadClass =
                Class.forName("android.app.ActivityThread");
        //find and load the main activity method
        final Method method = activityThreadClass.getMethod("currentApplication");
        return (Application) method.invoke(null, (Object[]) null);
    } catch (final java.lang.Throwable e) {
        // handle exception
        throw new IllegalArgumentException("No context could be retrieved!");
    }
}
 
Example 11
Project: OSchina_resources_android   File: AccountHelper.java   View source code 5 votes vote down vote up
public static void init(Application application) {
    if (instances == null)
        instances = new AccountHelper(application);
    else {
        // reload from source
        instances.user = SharedPreferencesHelper.loadFormSource(instances.application, User.class);
        TLog.d(TAG, "init reload:" + instances.user);
    }
}
 
Example 12
Project: Phial   File: PhialCore.java   View source code 5 votes vote down vote up
@NonNull
private static Page createShareView(Application application, ShareManager shareManager, AttachmentManager attachmentManager) {
    return new Page(
            SHARE_PAGE_KEY,
            R.drawable.ic_share,
            application.getString(R.string.share_page_title),
            new ShareViewFactory(shareManager, attachmentManager),
            Collections.<TargetScreen>emptySet()
    );
}
 
Example 13
Project: dhbw-timetable-android   File: DeviceBootReceiver.java   View source code 5 votes vote down vote up
@Override
public void onReceive(final Context context, final Intent intent) {
    if (intent.getAction() != null && intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        Log.i("BOOT", "Boot completed. Loading offline globals and resetup alarms");
        TimetableManager.getInstance().loadOfflineGlobals((Application) context.getApplicationContext(), () -> {
            AlarmSupervisor.getInstance().initialize();
            AlarmSupervisor.getInstance().rescheduleAllAlarms(context.getApplicationContext());
        });
    }
}
 
Example 14
Project: EazyBaseMVP   File: ClientModule.java   View source code 5 votes vote down vote up
@Provides
@Singleton
public Retrofit provideRetrofit(Application application, OkHttpClient okHttpClient, Retrofit.Builder builder, HttpUrl httpUrl, @Nullable RetrofitConfiguration configuration) {
    builder.baseUrl(httpUrl)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient);

    if (configuration != null) {
        configuration.configRetrofit(application, builder);
    }
    return builder.build();
}
 
Example 15
Project: Lantern-sdk   File: RYLA.java   View source code 5 votes vote down vote up
public RYLA setContext(String projectKey, Application application, String buildType) {
    if (buildType.equals("debug")) {
        return setContext(projectKey, application, true);
    } else {
        return setContext(projectKey, application, false);
    }
}
 
Example 16
Project: Android-skin-support   File: SkinActivityLifecycle.java   View source code 5 votes vote down vote up
public static SkinActivityLifecycle init(Application application) {
    if (sInstance == null) {
        synchronized (SkinActivityLifecycle.class) {
            if (sInstance == null) {
                sInstance = new SkinActivityLifecycle(application);
            }
        }
    }
    return sInstance;
}
 
Example 17
Project: PicShow-zhaipin   File: VideoPresenter.java   View source code 5 votes vote down vote up
@Inject
public VideoPresenter(VideoContract.Model model, VideoContract.View rootView
        , RxErrorHandler handler, Application application
        , ImageLoader imageLoader, AppManager appManager) {
    super(model, rootView);
    this.mErrorHandler = handler;
    this.mApplication = application;
    this.mImageLoader = imageLoader;
    this.mAppManager = appManager;
}
 
Example 18
Project: springreplugin   File: ActivityController.java   View source code 5 votes vote down vote up
public static final void install(Application application) {
    if (Build.VERSION.SDK_INT < 14) {
        if (LOG) {
            LogDebug.d(MAIN_TAG, "install activity watcher");
        }
        install2x();
        return;
    }

    if (LOG) {
        LogDebug.d(MAIN_TAG, "install activity lifecycle callbacks");
    }
    install4x(application);
}
 
Example 19
Project: Aurora   File: CategoryPresenter.java   View source code 5 votes vote down vote up
@Inject
public CategoryPresenter(CategoryContract.Model model, CategoryContract.View rootView
        , RxErrorHandler handler, Application application
        , ImageLoader imageLoader, AppManager appManager) {
    super(model, rootView);
    this.mErrorHandler = handler;
    this.mApplication = application;
    this.mImageLoader = imageLoader;
    this.mAppManager = appManager;
}
 
Example 20
Project: GitHub   File: PresenterManagerTest.java   View source code 5 votes vote down vote up
@Test
public void getPresenterReturnsNull(){
  Activity activity = Mockito.mock(Activity.class);
  Application application = Mockito.mock(Application.class);
  Mockito.when(activity.getApplication()).thenReturn(application);

  Assert.assertNull(PresenterManager.getPresenter(activity, "viewId123"));
}
 
Example 21
Project: GSoC-Info-Android   File: OrganizationViewModel.java   View source code 5 votes vote down vote up
public OrganizationViewModel(Application application) {
    super(application);
    organizations = GSoCApp.getOrgDao().getAllOrganizations()
            .create(null, new PagedList.Config.Builder()
                    .setPageSize(30)
                    .setPrefetchDistance(10)
                    .build());
}
 
Example 22
Project: EpubReaderAndroid   File: MainActivity.java   View source code 5 votes vote down vote up
Single<Epub> loadEpub() {
    if (epubSingle == null) {
        Application application = getApplication();
        epubSingle = Single.fromCallable(() -> Epub.fromUri(application, "file:///android_asset/The Silver Chair.epub"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .cache();
    }
    return epubSingle;
}
 
Example 23
Project: Android-Router   File: RemoteModule.java   View source code 5 votes vote down vote up
@RouterPath("/openRemoteActivity")
public void openRemoteActivity(Application context, String scheme, VPromise promise) {
    Intent intent = new Intent(context, RemoteActivity.class);
    intent.putExtra("tag", promise.getTag());
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
 
Example 24
Project: condom   File: CondomProcess.java   View source code 5 votes vote down vote up
/**
 * Install the condom protection for current process if it is not the default process.
 *
 * <p>This method must be called in {@link Application#onCreate()} to eliminate potential leakage.
 */
public static void installExceptDefaultProcess(final Application app, final CondomOptions options) {
	validateCondomOptions(options);
	final String current_process_name = getProcessName(app);
	if (current_process_name == null) return;
	final String default_process_name = app.getApplicationInfo().processName;
	if (! current_process_name.equals(default_process_name)) install(app, current_process_name, options);
}
 
Example 25
Project: chromium-for-android-56-debug-video   File: ExternalPrerenderHandler.java   View source code 5 votes vote down vote up
/**
 * Provides an estimate of the contents size.
 *
 * The estimate is likely to be incorrect. This is not a problem, as the aim
 * is to avoid getting a different layout and resources than needed at
 * render time.
 * @param application The application to use for getting resources.
 * @param convertToDp Whether the value should be converted to dp from pixels.
 * @return The estimated prerender size in pixels or dp.
 */
public static Rect estimateContentSize(Application application, boolean convertToDp) {
    // The size is estimated as:
    // X = screenSizeX
    // Y = screenSizeY - top bar - bottom bar - custom tabs bar
    // The bounds rectangle includes the bottom bar and the custom tabs bar as well.
    Rect screenBounds = new Rect();
    Point screenSize = new Point();
    WindowManager wm = (WindowManager) application.getSystemService(Context.WINDOW_SERVICE);
    wm.getDefaultDisplay().getSize(screenSize);
    Resources resources = application.getResources();
    int statusBarId = resources.getIdentifier("status_bar_height", "dimen", "android");
    try {
        screenSize.y -= resources.getDimensionPixelSize(statusBarId);
    } catch (Resources.NotFoundException e) {
        // Nothing, this is just a best effort estimate.
    }
    screenBounds.set(0,
            resources.getDimensionPixelSize(R.dimen.custom_tabs_control_container_height),
            screenSize.x, screenSize.y);

    if (convertToDp) {
        float density = resources.getDisplayMetrics().density;
        screenBounds.top = (int) Math.ceil(screenBounds.top / density);
        screenBounds.left = (int) Math.ceil(screenBounds.left / density);
        screenBounds.right = (int) Math.ceil(screenBounds.right / density);
        screenBounds.bottom = (int) Math.ceil(screenBounds.bottom / density);
    }
    return screenBounds;
}
 
Example 26
Project: PictureShow   File: TimeLinePageDataLoader.java   View source code 5 votes vote down vote up
public TimeLinePageDataLoader(Application context, LoadListener l) {
    mContext = (PictureShowApplication)context;
    mListener = l;
    notifier = new ChangeNotify(this, new Uri[] {
            MediaSetUtils.VIDEO_URI,
            MediaSetUtils.IMAGE_URI
    }, mContext);
}
 
Example 27
Project: support-application   File: EnvironmentCompat.java   View source code 5 votes vote down vote up
/**
 * application onCreate最前面调用
 *
 * @param application Application
 * @param defaultEnv  默认环境
 */
public void onApplicationCreate(Application application, Env defaultEnv) {
    try {
        SharedPreferences sharedPreferences = application.getSharedPreferences(KEY, Context.MODE_PRIVATE);
        String persistEnv = sharedPreferences.getString(KEY, defaultEnv.name());
        this.env = Env.valueOf(persistEnv);
    } catch (Exception e) {
        e.printStackTrace();
        this.env = Env.RELEASE;
    }
}
 
Example 28
Project: BuildingDebugFeatures   File: DebugNetworkModule.java   View source code 5 votes vote down vote up
@Override
OkHttpClient.Builder okHttpClientBuilder(Application application) {
    OkHttpClient.Builder builder = super.okHttpClientBuilder(application)
            .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .addInterceptor(new StethoInterceptor());

    if (new DebugPreferences(application).isChuckEnabled()) {
        builder.addInterceptor(new ChuckInterceptor(application));
    }
    return builder;
}
 
Example 29
Project: Aurora   File: HistoryPresenter.java   View source code 5 votes vote down vote up
@Inject
public HistoryPresenter(HistoryContract.Model model, HistoryContract.View rootView
        , RxErrorHandler handler, Application application
        , ImageLoader imageLoader, AppManager appManager) {
    super(model, rootView);
    this.mErrorHandler = handler;
    this.mApplication = application;
    this.mImageLoader = imageLoader;
    this.mAppManager = appManager;
}
 
Example 30
Project: weex-3d-map   File: WXSDKEngine.java   View source code 5 votes vote down vote up
/**
 * Deprecated. Use {@link #initialize(Application, InitConfig)} instead.
 */
@Deprecated
public static void init(Application application, IWXUserTrackAdapter utAdapter, String framework) {
  initialize(application,
    new InitConfig.Builder()
      .setUtAdapter(utAdapter)
      .build()
  );
}
 
Example 31
Project: LQRBiliBlili   File: VideoDetailPresenter.java   View source code 5 votes vote down vote up
@Inject
public VideoDetailPresenter(VideoDetailContract.Model model, VideoDetailContract.View rootView
        , RxErrorHandler handler, Application application
        , ImageLoader imageLoader, AppManager appManager) {
    super(model, rootView);
    this.mErrorHandler = handler;
    this.mApplication = application;
    this.mImageLoader = imageLoader;
    this.mAppManager = appManager;
    RetrofitUrlManager.getInstance().putDomain("video_detail_summary", Api.VIDEO_DETAIL_SUMMARY_BASE_URL);
    RetrofitUrlManager.getInstance().putDomain("video_detail_reply", Api.VIDEO_DETAIL_REPLY_BASE_URL);
}
 
Example 32
Project: GmArchMvvm   File: AppManager.java   View source code 4 votes vote down vote up
@Inject
public AppManager(Application application) {
    this.mApplication = application;
    EventBus.getDefault().register(this);
}
 
Example 33
Project: APIJSON-Android-RxJava   File: ApplicationTest.java   View source code 4 votes vote down vote up
public ApplicationTest() {
    super(Application.class);
}
 
Example 34
Project: MVVMFrames   File: LoginPresenter.java   View source code 4 votes vote down vote up
@Inject
public LoginPresenter(Application application, LoginContract.Model model, LoginContract.View view) {
    super(model, view);
    this.application = (MVPApplication) application;
}
 
Example 35
Project: com.ruuvi.station   File: Foreground.java   View source code 4 votes vote down vote up
public static Foreground get(Application application){
    if (instance == null) {
        init(application);
    }
    return instance;
}
 
Example 36
Project: MoligyMvpArms   File: AppManager.java   View source code 4 votes vote down vote up
@Inject
public AppManager(Application application) {
    this.mApplication = application;
    EventBus.getDefault().register(this);
}
 
Example 37
Project: GitHub   File: ApplicationTest.java   View source code 4 votes vote down vote up
public ApplicationTest() {
    super(Application.class);
}
 
Example 38
Project: XYSeekBar   File: ApplicationTest.java   View source code 4 votes vote down vote up
public ApplicationTest() {
    super(Application.class);
}
 
Example 39
Project: AndroidSnooper   File: AndroidSnooper.java   View source code 4 votes vote down vote up
public static AndroidSnooper init(Application application) {
  if (androidSnooper == null) {
    androidSnooper = new AndroidSnooper();
  }
  return androidSnooper;
}
 
Example 40
Project: Bailan   File: RxRetrofitApp.java   View source code 4 votes vote down vote up
private static void setApplication(Application application) {
    RxRetrofitApp.application = application;
}