我想檢查我的應用程序是否在背景或前景,我也希望您在打開的應用程序或不使用廣播接收器如何檢查應用程序在前臺的後臺運行在廣播接收器
public class CheckRunningApplicationReceiver extends BroadcastReceiver {
Context mContext;
public int mId = 1000;
NotificationManager mNotificationManager;
@Override
public void onReceive(Context aContext, Intent anIntent) {
mContext = aContext;
Boolean isAppOpen = isApplicationSentToBackground(aContext);
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (isAppOpen) {
//openNotification();
} else {
//mNotificationManager.cancel(mId);
}
}
private void openNotification() {// Instantiate notification with icon and
// ticker message
Notification notification = new Notification(R.drawable.ic_launcher,"Notification message!", System.currentTimeMillis());
PendingIntent i = PendingIntent.getActivity(mContext, 0, new Intent(mContext,MainActivity.class), 0);
notification.setLatestEventInfo(mContext, "Notification Created","Click here to see the message", i);
notification.flags = Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify(mId, notification);
}
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;
}
}
是否有任何解決方案,幫助我, 謝謝。
我不知道,如果這個工程,但你可以試試這個http://stackoverflow.com/questions/3667022/檢查,如果一個Android應用程序正在運行在背景中/ 5862048#5862048 –
我已經取得了巨大的成功與來自史蒂夫Liles在這篇博文中的代碼:[我的Android應用程序當前前景或背景?](http://steveliles.github.io/is_my_android_app_currently_foreground_or_background.html) –