Отображать push-уведомление в поле предупреждения, когда приложение работает на переднем плане
Я делаю push-уведомление в своем приложении для Android, которое запускается GCM. Я хочу отобразить уведомление, если приложение запущено в окне предупреждения, если приложение не работает, а не на переднем плане, просто отображает уведомление в строке состояния. Как определить, запущено ли приложение и находится ли оно на переднем плане? это возможно, чтобы показать уведомление, подобное этому. Теперь я использую этот код для уведомления о статусе строки состояния
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, BottomActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
Ответы
Ответ 1
Вы можете создать новую Работу и тему как Диалог и проверить активность переднего плана. Проверьте ниже код.
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager
.getRunningTasks(Integer.MAX_VALUE);
boolean isActivityFound = false;
if (services.get(0).topActivity.getPackageName().toString()
.equalsIgnoreCase(context.getPackageName().toString())) {
isActivityFound = true;
}
if (isActivityFound) {
resultIntent = new Intent(context, AlertDialogNotification.class);
resultIntent.putExtra(EXTRA_ALERT_MESSAGE_BEAUTIFUL, "anyMessage");
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(resultIntent);
}
В манифесте сделайте тему диалогом для действия. Надеюсь, поможет. Сообщите нам, если у вас есть проблема.
Ответ 2
Сколько у вас действий? Если только один, довольно просто сохранить одноэлементную ссылку на него между onResume() и onPause() (AKA, когда он активен), и вызвать активность из получателя, если это так. если у вас много действий, вы можете достичь аналогичной логики, имея для них общий базовый класс. Что-то вроде этого:
class MyActivity: Activity
{
static private MyActivity _Current = null;
protected void onResume() //Activated
{
super.onResume();
_Current = this;
}
protected void onPause() //Deactivated
{
super.onPause();
_Current = null;
}
//This is for the receiver to call
static public PopAlert()
{
if(_Current != null)
{
new AlertDialog.Builder(_Current)
.setMessage("Hello world")
//More alert setup; use _Current as a context object
.create().show();
}
}
}
Ответ 3
попробуйте эти
public static boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName()))
isInBackground = false;
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}