簡體   English   中英

以編程方式將 Android 應用程序從后台帶回

[英]Bring Android app back from background programmatically

我是 Android 編碼的新手,但我已經玩過 java。

我想在后台打開或恢復我的應用程序。

我一直在四處尋找,但似乎沒有任何效果。

我有一個 class 的 function ,每次收到通知時都會調用它,它是CordovaNotificationReceivedHandler ,它由 OneSignal init 按照下面的代碼進行實例化。

OneSignal.init(this.cordova.getActivity(),
              googleProjectNumber,
              appId,
              new CordovaNotificationOpenedHandler(notifOpenedCallbackContext),
              new CordovaNotificationReceivedHandler(notifReceivedCallbackContext)
      );

試圖讓我的應用程序重新排序和顯示,即使用戶在另一個應用程序中,我也做了以下更改:

OneSignal.init(this.cordova.getActivity(),
              googleProjectNumber,
              appId,
              new CordovaNotificationOpenedHandler(notifOpenedCallbackContext),
              new CordovaNotificationReceivedHandler(this.cordova.getActivity(), notifReceivedCallbackContext));

在收到推送通知時調用的 function 的正文中,我添加了以下代碼:

Intent it = new Intent("intent.my.action");
      it.setComponent(new ComponentName(contextActivy.getPackageName(), MainActivity.class.getName()));
      it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      contextActivy.getApplicationContext().startActivity(it);
      this.handleActivityLifecycleHandler();

Como a classe ficou após a modificação:

private class CordovaNotificationReceivedHandler implements NotificationReceivedHandler {

    private CallbackContext jsNotificationReceivedCallBack;
    private Context contextActivy;

    public CordovaNotificationReceivedHandler(Context contextActivy, CallbackContext inCallbackContext) {
      jsNotificationReceivedCallBack = inCallbackContext;
      this.contextActivy = contextActivy;
    }

    @Override
    public void notificationReceived(OSNotification notification) {
      Log.w("Got here","Aqui");

      Intent it = new Intent("intent.my.action");
      it.setComponent(new ComponentName(contextActivy.getPackageName(), MainActivity.class.getName()));
      it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      contextActivy.getApplicationContext().startActivity(it);
      this.handleActivityLifecycleHandler();

      try {
        CallbackHelper.callbackSuccess(jsNotificationReceivedCallBack, new JSONObject(notification.stringify()));
      }
      catch (Throwable t) {
        t.printStackTrace();
      }
    } 
}

問題是應用程序沒有重新排序以應用或打開。

重要的是要記住,我假設應用程序應該是打開的。

你可以使用它,它工作正常。

        Intent intent = new Intent("intent.my.action");
        intent.setComponent(new ComponentName(this, yourActivity.class));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(intent);

不要忘記在清單中的活動中添加此內容

        <intent-filter>
            <action android:name="intent.my.action" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM