仅当应用程序未运行 android 时才显示推送通知 [英] Show push notification only when app is not running android

查看:22
本文介绍了仅当应用程序未运行 android 时才显示推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我将推送通知与 GCM 集成.每当通知出现时,它都可以正常工作.但是即使用户在应用程序内,也会推送通知.我希望只有当用户不在应用程序时才显示通知.

这是我的推送通知代码:

<块引用>

GcmBroadcastReceiver

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {@覆盖public void onReceive(上下文上下文,意图意图){ComponentName comp = new ComponentName(GCMNotificationIntentService.class.getPackage().getName(),GCMNotificationIntentService.class.getName());startWakefulService(context, (intent.setComponent(comp)));setResultCode(Activity.RESULT_OK);}}

<块引用>

GCMnotificationIntentService.Class

public class GCMNotificationIntentService extends IntentService {公共静态 int notificationId = 10;私有 NotificationManager mNotificationManager;NotificationCompat.Builder 构建器;私人布尔登录状态=假;公共 GCMNotificationIntentService() {超级(GcmIntentService");}public static final String TAG = GCMNotificationIntentService.class.getSimpleName();@覆盖受保护的无效 onHandleIntent(意图意图){Bundle extras = intent.getExtras();GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);//getMessageType() 意图参数必须是你收到的意图//在你的广播接收器中.String messageType = gcm.getMessageType(intent);if ( !extras.isEmpty() ) {//有解包的效果/** 根据消息类型过滤消息.因为很有可能* GCM 将在未来扩展新的消息类型,只是* 忽略您不感兴趣的任何消息类型,或者您* 不认识.*/if ( GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType) ) {sendNotification("发送错误:" + extras.toString());} else if ( GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType) ) {sendNotification("服务器上已删除的消息:" + extras.toString());//如果是常规 GCM 消息,请做一些工作.} else if ( GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType) ) {sendNotification(extras.getString("message"));Log.i(TAG, "收到:" + extras.toString());}}//释放 WakefulBroadcastReceiver 提供的唤醒锁.GcmBroadcastReceiver.completeWakefulIntent(intent);}私人无效发送通知(字符串味精){mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(getString(R.string.notification_title)).setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);mBuilder.setSound(uri);mBuilder.setContentIntent(contentIntent);mBuilder.setAutoCancel(true);mNotificationManager.notify(notificationId++, mBuilder.build());}}

<块引用>

在清单文件中

 <接收者android:name=".GcmBroadcastReceiver"android:permission="com.google.android.c2dm.permission.SEND" ><意图过滤器><action android:name="com.google.android.c2dm.intent.RECEIVE"/><action android:name="com.google.android.c2dm.intent.REGISTRATION"/><category android:name="com.medlife.deliveryagent"/></意图过滤器></接收器><service android:name=".GCMNotificationIntentService"/>

任何建议将不胜感激!!!

解决方案

通过调用下面的方法并根据返回值 true 或 false 来检查您的应用程序是否在前台执行您的其余工作

>

public boolean checkApp(){ActivityManager am = (ActivityManager) 这个.getSystemService(ACTIVITY_SERVICE);//从当前运行的任务中获取信息列表taskInfo = am.getRunningTasks(1);ComponentName componentInfo = taskInfo.get(0).topActivity;if (componentInfo.getPackageName().equalsIgnoreCase("YourPackage")) {返回真;} 别的 {返回假;}}

In my application I have push notification integrated with GCM. Its working fine whenever notification comes its appearing. But push notification come even when user is inside the app. I want notifications to appear only when user is outside the app.

Here is my code for push notification:

GcmBroadcastReceiver

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    ComponentName comp = new ComponentName(GCMNotificationIntentService.class.getPackage().getName(), 
            GCMNotificationIntentService.class.getName());
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}
}

GCMnotificationIntentService.Class

public class GCMNotificationIntentService extends IntentService {

public static int notificationId = 10;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
private boolean login_status = false;


public GCMNotificationIntentService() {
    super("GcmIntentService");
}

public static final String TAG = GCMNotificationIntentService.class.getSimpleName();

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if ( !extras.isEmpty() ) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that
         * GCM will be extended in the future with new message types, just
         * ignore any message types you're not interested in, or that you
         * don't recognize.
         */
        if ( GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType) ) {
            sendNotification("Send error: " + extras.toString());
        } else if ( GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType) ) {
            sendNotification("Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
        } else if ( GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType) ) {
            sendNotification(extras.getString("message"));
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(String msg) {

    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getString(R.string.notification_title))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);
    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    mBuilder.setSound(uri);
    mBuilder.setContentIntent(contentIntent);
    mBuilder.setAutoCancel(true);
    mNotificationManager.notify(notificationId++, mBuilder.build());
}
}

In ManifestFile

 <receiver
        android:name=".GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="com.medlife.deliveryagent" />
        </intent-filter>
    </receiver>
  <service android:name=".GCMNotificationIntentService" />

Any suggestions would be highly appreciated!!!

解决方案

Do something like this to check whether you app is in foreground or not by calling below method and depending on returning value true or false do your rest of work

public boolean checkApp(){
       ActivityManager am = (ActivityManager) this
                .getSystemService(ACTIVITY_SERVICE);

        // get the info from the currently running task
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equalsIgnoreCase("YourPackage")) {
            return true;
        } else {
           return false;
        }
  } 

这篇关于仅当应用程序未运行 android 时才显示推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆