显示推送通知,只有当应用程序无法运行Android [英] Show push notification only when app is not running android

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

问题描述

在我的应用我有集成推送通知GCM 。它的做工精细,每当谈到通知其出现。但是,当用户在应用内推送通知来连。我想通知显示,只有当用户的应用程序之外。

下面是我的code的推送通知:


  

GcmBroadcastReceiver


 公共类GcmBroadcastReceiver扩展WakefulBroadcastReceiver {@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
    组件名补偿=新的组件名(GCMNotificationIntentService.class.getPackage()的getName()
            GCMNotificationIntentService.class.getName());
    startWakefulService(上下文,(intent.setComponent(化合物)));
    的setResult code(Activity.RESULT_OK);
}
}


  

GCMnotificationIntentService.Class


 公共类GCMNotificationIntentService扩展IntentService {公共静态INT notificationId = 10;
私人NotificationManager mNotificationManager;
NotificationCompat.Builder建设者;
私人布尔login_status = FALSE;
公共GCMNotificationIntentService(){
    超级(GcmIntentService);
}公共静态最后的字符串标记= GCMNotificationIntentService.class.getSimpleName();@覆盖
保护无效onHandleIntent(意向意图){
    捆绑额外= intent.getExtras();
    Google云端通讯GCM = GoogleCloudMessaging.getInstance(本);
    //该getMessageType()意图参数必须是您收到的意图
    //你的广播接收器。
    字符串为messageType = gcm.getMessageType(意向);    如果(!extras.isEmpty()){//具有unparcelling捆绑的效果
        / *
         *根据消息类型过滤消息。因为它很可能是
         * GCM将在未来与新的消息类型被延长,只是
         *忽略你不感兴趣的任何消息类型,或者说你
         *不承认。
         * /
        如果(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(为messageType)){
            sendNotification的(发送错误:+ extras.toString());
        }否则如果(GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(为messageType)){
            sendNotification的(在服务器上删除的邮件:+ extras.toString());
            //如果是一个普通GCM消息,做了一些工作。
        }否则如果(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(为messageType)){
            sendNotification时(extras.getString(信息));
            Log.i(TAG,收到:+ extras.toString());
        }
    }
    //释放该WakefulBroadcastReceiver提供的唤醒锁。
    GcmBroadcastReceiver.completeWakefulIntent(意向);
}私人无效sendNotification时(弦乐味精){    mNotificationManager =(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);    的PendingIntent contentIntent = PendingIntent.getActivity(这一点,0,意向,PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder =新NotificationCompat.Builder(本).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(的getString(R.string.notification_title))
            .setStyle(新NotificationCompat.BigTextStyle()bigText(MSG))setContentText(MSG)。
    URI URI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    mBuilder.setSound(URI);
    mBuilder.setContentIntent(co​​ntentIntent);
    mBuilder.setAutoCancel(真);
    mNotificationManager.notify(notificationId ++ mBuilder.build());
}
}


  

在ManifestFile


 <接收
        机器人:名字=。GcmBroadcastReceiver
        机器人:权限=com.google.android.c2dm.permission.SEND>
        &所述;意图滤光器>
            <作用机器人:名字=com.google.android.c2dm.intent.RECEIVE/>
            <作用机器人:名字=com.google.android.c2dm.intent.REGISTRATION/>            <类机器人:名字=com.medlife.deliveryagent/>
        &所述; /意图滤光器>
    < /接收器>
  <服务机器人。GCMNotificationIntentServiceNAME = />

任何建议将是非常美联社preciated!


解决方案

做这样的事情,检查是否应用程序是在前台还是不通过调用下面的方法,并根据返回值true或false做你的工作,休息

 公共布尔checkApp(){
       ActivityManager AM =(ActivityManager)本
                .getSystemService(ACTIVITY_SERVICE);        //从当前运行的任务的信息
        清单< ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);        组件名componentInfo = taskInfo.get(0).topActivity;
        如果(componentInfo.getPackageName()。equalsIgnoreCase(YourPackage)){
            返回true;
        }其他{
           返回false;
        }
  }

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天全站免登陆