Начните активность, нажав на уведомление Android - PullRequest
0 голосов
/ 25 мая 2018

Я использую сервис Onesignal для отправки уведомлений в мое приложение.Я установил приложение, чтобы открывать определенное действие AboutActivity.class всякий раз, когда я нажимаю на уведомление.Проблема в том, что когда приложение работает в фоновом режиме, и я нажимаю на уведомление, приложение переводит меня на MainActivity.class, а не на запланированное действие, которое составляет AboutActivity.class.Если приложение NOT работает в фоновом режиме, и я нажимаю на уведомление, оно работает нормально и открывает запланированное действие.Мой вопрос заключается в том, как я могу заставить приложение открывать запланированное действие, которое AboutActivity.class, если приложение работает в фоновом режиме (возобновить приложение) или нет.Вот мои коды

MyNotificationExtenderService

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.onesignal.NotificationExtenderService;
import com.onesignal.OSNotificationDisplayedResult;
import com.onesignal.OSNotificationReceivedResult;

import java.math.BigInteger;


public class MyNotificationExtenderService extends NotificationExtenderService {
@Override
protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
    OverrideSettings overrideSettings = new OverrideSettings();
    overrideSettings.extender = new NotificationCompat.Extender() {
        @Override
        public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
            // Sets the background notification color to Red on Android 5.0+ devices.
            Bitmap icon = BitmapFactory.decodeResource(MyApplication.getContext().getResources(),
                    R.drawable.ic_stat_onesignal_default);
            builder.setLargeIcon(icon);
            return builder.setColor(new BigInteger("FF0000FF", 16).intValue());
        }
    };

    OSNotificationDisplayedResult displayedResult = displayNotification(overrideSettings);
    Log.d("OneSignalExample", "Notification displayed with id: " + displayedResult.androidNotificationId);

    return true;
}
}

MyNotificationReceivedHandler

import android.util.Log;

import com.onesignal.OSNotification;
import com.onesignal.OneSignal;

import org.json.JSONObject;



public class MyNotificationReceivedHandler  implements OneSignal.NotificationReceivedHandler {
@Override
public void notificationReceived(OSNotification notification) {
    JSONObject data = notification.payload.additionalData;
    String notificationID = notification.payload.notificationID;
    String title = notification.payload.title;
    String body = notification.payload.body;
    String smallIcon = notification.payload.smallIcon;
    String largeIcon = notification.payload.largeIcon;
    String bigPicture = notification.payload.bigPicture;
    String smallIconAccentColor = notification.payload.smallIconAccentColor;
    String sound = notification.payload.sound;
    String ledColor = notification.payload.ledColor;
    int lockScreenVisibility = notification.payload.lockScreenVisibility;
    String groupKey = notification.payload.groupKey;
    String groupMessage = notification.payload.groupMessage;
    String fromProjectNumber = notification.payload.fromProjectNumber;
    String rawPayload = notification.payload.rawPayload;

    String customKey;

    Log.i("OneSignalExample", "NotificationID received: " + notificationID);

    if (data != null) {
        customKey = data.optString("customkey", null);
        if (customKey != null)
            Log.i("OneSignalExample", "customkey set with value: " + customKey);
    }
}
}

MyNotificationOpenedHandler

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OSNotification;
import com.onesignal.OneSignal;

import org.json.JSONObject;


 public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
private Context mContext;
public MyNotificationOpenedHandler (Context context) {
   mContext = context;
}
  @Override
  public void notificationOpened(OSNotificationOpenResult result) {
    OSNotificationAction.ActionType actionType = result.action.type;
    JSONObject data = result.notification.payload.additionalData;
    String launchUrl = result.notification.payload.launchURL; // update docs launchUrl

    String customKey;
    String openURL = null;
    Object activityToLaunch = AboutActivity.class;

    if (data != null) {


        Intent intent = new Intent(mContext, (Class<?>) activityToLaunch);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("openURL", openURL);
        Log.i("OneSignalExample", "openURL = " + openURL);
        mContext.startActivity(intent);

    }}
}

И, конечно, часть инициализации в MainActivity

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    OneSignal.startInit(this)
            .setNotificationReceivedHandler(new MyNotificationReceivedHandler())
            .setNotificationOpenedHandler(new MyNotificationOpenedHandler(this))
            .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
            .unsubscribeWhenNotificationsAreDisabled(true)
            .init();
...