我是android的新手。我有基于客户端服务器的应用程序。服务器每隔一分钟就会继续向客户端发送更新通知,而在客户端,我的应用程序会接收这些更新并使用Toast显示。但现在我的问题是,只要我的客户端应用程序进入后台,服务器就会继续发送更新通知,而我的客户端显示它时,就好像应用程序在前台一样。我不知道如何检查应用程序是否在后台运行。
发布于 2010-07-06 14:49:18
http://developer.android.com/guide/topics/fundamentals.html#lcycles是对安卓应用程序生命周期的描述。
当活动进入后台时,将调用onPause()方法。因此,您可以在此方法中停用更新通知。
发布于 2012-02-16 23:07:26
更新,请先看看这个:
Checking if an Android application is running in the background
要检查应用程序是否被发送到后台,您可以在应用程序中的每个活动上调用onPause()上的以下代码:
/**
* Checks if the application is being sent in the background (i.e behind
* another application's Activity).
*
* @param context the context
* @return <code>true</code> if another application will be above this one.
*/
public static boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}为了让它起作用,你应该在你的AndroidManifest.xml中包含这个
<uses-permission android:name="android.permission.GET_TASKS" />发布于 2016-03-31 05:16:25
仅限应用编程接口级别14及以上的
您可以对activity、service等使用ComponentCallbacks2。
示例:
public class MainActivity extends AppCompatActivity implements ComponentCallbacks2 {
@Override
public void onConfigurationChanged(final Configuration newConfig) {
}
@Override
public void onLowMemory() {
}
@Override
public void onTrimMemory(final int level) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
// app is in background
}
}
}https://stackoverflow.com/questions/3183932
复制相似问题