当用户点击Android设备

时间:2016-07-19 11:42:02

标签: android google-cloud-messaging android-notifications

当应用程序不在前台时,如果用户点击通知,如果用户收到消息,他注意到它正在收到通知,当用户点击它后导航到应用程序时,如何将信息传递给Android应用程序,问题是应用程序以默认状态打开,我想首先导航到消息传递页面。

public class MyGcmListenerService extends GcmListenerService {

private static final String TAG = "MyGcmListenerService";
private UserDetails userDetails;

/**
 * Called when message is received.
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);
    Log.d(TAG, "Data" + data);

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */
    if(isAppOnForeground()){
        //Toast.makeText(getApplication(), data.toString(),Toast.LENGTH_LONG).show();
    }else{
        sendNotification(message);
        return;
        //sendNotification("You are not in the app");
    }

}

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received.
 */
private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.two_grow_icon)
            .setContentTitle("Test")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

//Function that check if the application in foreground
private boolean isAppOnForeground() {
    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
        return false;
    }
    final String packageName = getPackageName();
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
            return true;
        }
    }
    return false;
}

}

0 个答案:

没有答案