Checking if an Android application is running in the background

前端 未结 30 2858
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  无人及你
    2020-11-21 07:05

    In my activities onResume and onPause I write an isVisible boolean to SharedPrefences.

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        Editor editor = sharedPrefs.edit();
        editor.putBoolean("visible", false);
        editor.commit();
    

    And read it elsewhere when needed via,

        // Show a Toast Notification if App is not visible (ie in background. Not running, etc) 
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        if(!sharedPrefs.getBoolean("visible", true)){...}
    

    Maybe not elegant, but it works for me...

提交回复
热议问题