Skip to content

Commit e401f24

Browse files
committed
Bug fixes
* Correctly sets isActive to true when it should be when enableInAppAlertNotification is set to true. * Now handles switching over to a new Activity if it is finished, it implements the NotificationOpenedHandler interface, and OneSignal.init is called on the new Activity. - Added a TiedToCurrentActivity annotation to give the same effect as above without needing to add the NotificationOpenedHandler interface to your Activities.
1 parent 05efe22 commit e401f24

File tree

5 files changed

+135
-39
lines changed

5 files changed

+135
-39
lines changed

OneSignalSDK/app/src/main/java/com/onesignal/example/MainActivity.java

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414
import org.json.JSONException;
1515
import org.json.JSONObject;
1616

17+
import java.lang.reflect.Field;
18+
import java.util.HashMap;
19+
1720

1821
public class MainActivity extends ActionBarActivity {
1922

@@ -32,23 +35,23 @@ protected void onCreate(Bundle savedInstanceState) {
3235
// Pass in your app's Context, Google Project number, OneSignal App ID, and a NotificationOpenedHandler
3336
OneSignal.init(this, "703322744261", "b2f7f966-d8cc-11e4-bed1-df8f05be55ba", new ExampleNotificationOpenedHandler());
3437
//OneSignal.init(this, "703322744261", "5eb5a37e-b458-11e3-ac11-000c2940e62c", new ExampleNotificationOpenedHandler());
35-
//OneSignal.enableInAppAlertNotification(true);
38+
OneSignal.enableInAppAlertNotification(false);
3639
OneSignal.enableNotificationsWhenActive(true);
3740
//OneSignal.setSubscription(false);
3841

39-
// OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
40-
// @Override
41-
// public void idsAvailable(String userId, String registrationId) {
42-
// Log.i("OneSignal Example:", "UserID: " + userId + ", RegId: " + (registrationId != null ? registrationId : "null"));
43-
//
44-
// try {
45-
// // OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + userId + "']}"));
46-
// OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + "86480bb0-ef9a-11e4-8cf1-000c29917011', '2def6d7a-4395-11e4-890a-000c2940e62c" + "']}"), null);
47-
// } catch (JSONException e) {
48-
// e.printStackTrace();
49-
// }
50-
// }
51-
// });
42+
OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
43+
@Override
44+
public void idsAvailable(String userId, String registrationId) {
45+
Log.i("OneSignal Example:", "UserID: " + userId + ", RegId: " + (registrationId != null ? registrationId : "null"));
46+
47+
try {
48+
OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + userId + "']}"), null);
49+
//OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + "86480bb0-ef9a-11e4-8cf1-000c29917011', '2def6d7a-4395-11e4-890a-000c2940e62c" + "']}"), null);
50+
} catch (JSONException e) {
51+
e.printStackTrace();
52+
}
53+
}
54+
});
5255
}
5356

5457
@Override
@@ -85,6 +88,7 @@ public boolean onOptionsItemSelected(MenuItem item) {
8588
}
8689

8790
// NotificationOpenedHandler is implemented in its own class instead of adding implements to MainActivity so we don't hold on to a reference of our first activity if it gets recreated.
91+
@OneSignal.TiedToCurrentActivity
8892
private class ExampleNotificationOpenedHandler implements NotificationOpenedHandler {
8993
/**
9094
* Callback to implement in your app to handle when a notification is opened from the Android status bar or
@@ -97,7 +101,7 @@ private class ExampleNotificationOpenedHandler implements NotificationOpenedHand
97101
*/
98102
@Override
99103
public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
100-
String messageTitle = "OneSignal Example", messageBody = message;
104+
String messageTitle = "OneSignal Example:" + isActive, messageBody = message;
101105

102106
try {
103107
if (additionalData != null) {

OneSignalSDK/app/src/main/java/com/onesignal/example/MainActivity2Activity.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,32 @@
11
package com.onesignal.example;
22

3+
import android.app.Activity;
34
import android.support.v7.app.ActionBarActivity;
45
import android.os.Bundle;
6+
import android.support.v7.app.AlertDialog;
57
import android.view.Menu;
68
import android.view.MenuItem;
79

10+
import com.onesignal.OneSignal;
11+
12+
import org.json.JSONException;
13+
import org.json.JSONObject;
14+
815

916
public class MainActivity2Activity extends ActionBarActivity {
1017

18+
private static Activity currentActivity;
19+
20+
1121
@Override
1222
protected void onCreate(Bundle savedInstanceState) {
1323
super.onCreate(savedInstanceState);
1424
setContentView(R.layout.activity_main_activity2);
25+
26+
currentActivity = this;
27+
28+
OneSignal.init(this, "703322744261", "b2f7f966-d8cc-11e4-bed1-df8f05be55ba", new ExampleNotificationOpenedHandler());
29+
OneSignal.enableNotificationsWhenActive(true);
1530
}
1631

1732
@Override
@@ -35,4 +50,38 @@ public boolean onOptionsItemSelected(MenuItem item) {
3550

3651
return super.onOptionsItemSelected(item);
3752
}
53+
54+
private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
55+
/**
56+
* Callback to implement in your app to handle when a notification is opened from the Android status bar or
57+
* a new one comes in while the app is running.
58+
* This method is located in this activity as an example, you may have any class you wish implement NotificationOpenedHandler and define this method.
59+
*
60+
* @param message The message string the user seen/should see in the Android status bar.
61+
* @param additionalData The additionalData key value pair section you entered in on onesignal.com.
62+
* @param isActive Was the app in the foreground when the notification was received.
63+
*/
64+
@Override
65+
public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
66+
String messageTitle = "OneSignal Example2:" + isActive, messageBody = message;
67+
68+
try {
69+
if (additionalData != null) {
70+
if (additionalData.has("title"))
71+
messageTitle = additionalData.getString("title");
72+
if (additionalData.has("actionSelected"))
73+
messageBody += "\nPressed ButtonID: " + additionalData.getString("actionSelected");
74+
75+
messageBody = message + "\n\nFull additionalData:\n" + additionalData.toString();
76+
}
77+
} catch (JSONException e) {}
78+
79+
new AlertDialog.Builder(MainActivity2Activity.currentActivity)
80+
.setTitle(messageTitle)
81+
.setMessage(messageBody)
82+
.setCancelable(true)
83+
.setPositiveButton("OK", null)
84+
.create().show();
85+
}
86+
}
3887
}

OneSignalSDK/onesignal/src/main/java/com/onesignal/GenerateNotification.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,17 +100,17 @@ public void onClick(DialogInterface dialog, int which) {
100100

101101
Bundle bundle = new Bundle(gcmBundle);
102102
bundle.putString("custom", customJson.toString());
103-
OneSignal.handleNotificationOpened(context, bundle);
103+
OneSignal.handleNotificationOpened(bundle);
104104
} catch (Throwable t) {}
105105
}
106106
else
107-
OneSignal.handleNotificationOpened(context, gcmBundle);
107+
OneSignal.handleNotificationOpened(gcmBundle);
108108
}
109109
};
110110
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
111111
@Override
112112
public void onCancel(DialogInterface dialogInterface) {
113-
OneSignal.handleNotificationOpened(context, gcmBundle);
113+
OneSignal.handleNotificationOpened(gcmBundle);
114114
}
115115
});
116116

OneSignalSDK/onesignal/src/main/java/com/onesignal/OneSignal.java

Lines changed: 61 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
import java.io.PrintWriter;
3131
import java.io.StringWriter;
3232
import java.io.UnsupportedEncodingException;
33+
import java.lang.annotation.ElementType;
34+
import java.lang.annotation.Retention;
35+
import java.lang.annotation.RetentionPolicy;
36+
import java.lang.annotation.Target;
3337
import java.lang.reflect.Field;
3438
import java.util.ArrayList;
3539
import java.util.Calendar;
@@ -59,6 +63,7 @@
5963
import android.net.Uri;
6064
import android.os.Build;
6165
import android.os.Bundle;
66+
import android.os.Looper;
6267
import android.os.SystemClock;
6368
import android.util.Log;
6469
import android.util.TypedValue;
@@ -72,6 +77,10 @@ public enum LOG_LEVEL {
7277
NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
7378
}
7479

80+
@Retention(RetentionPolicy.RUNTIME)
81+
@Target(ElementType.TYPE)
82+
public @interface TiedToCurrentActivity {}
83+
7584
public interface NotificationOpenedHandler {
7685
/**
7786
* Callback to implement in your app to handle when a notification is
@@ -130,14 +139,17 @@ public interface PostNotificationResponseHandler {
130139
private static TrackGooglePurchase trackGooglePurchase;
131140
private static TrackAmazonPurchase trackAmazonPurchase;
132141

133-
public static final String VERSION = "010900";
142+
public static final String VERSION = "010901";
134143

135144
private static PushRegistrator pushRegistrator;
136145
private static AdvertisingIdentifierProvider mainAdIdProvider = new AdvertisingIdProviderGPS();
137146

138147
private static int deviceType;
139148
public static String sdkType = "native";
140149

150+
private static JSONObject nextInitAdditionalDataJSON = null;
151+
private static String nextInitMessage = null;
152+
141153
public static void init(Activity context, String googleProjectNumber, String oneSignalAppId) {
142154
init(context, googleProjectNumber, oneSignalAppId, null);
143155
}
@@ -184,8 +196,23 @@ public static void init(Activity context, String googleProjectNumber, String one
184196
currentSubscription = -4;
185197
}
186198

187-
if (initDone)
199+
if (initDone) {
200+
if (context != null)
201+
appContext = context;
202+
if (inNotificationOpenedHandler != null)
203+
notificationOpenedHandler = inNotificationOpenedHandler;
204+
205+
onResumed();
206+
207+
if (nextInitMessage != null && notificationOpenedHandler != null) {
208+
fireNotificationOpenedHandler(nextInitMessage, nextInitAdditionalDataJSON, false);
209+
210+
nextInitMessage = null;
211+
nextInitAdditionalDataJSON = null;
212+
}
213+
188214
return;
215+
}
189216

190217
// END: Init validation
191218

@@ -236,12 +263,16 @@ public void complete(String id) {
236263

237264
// Called from tapping on a Notification from the status bar when the activity is completely dead and not open in any state.
238265
if (appContext.getIntent() != null && appContext.getIntent().getBundleExtra("data") != null)
239-
runNotificationOpenedCallback(appContext.getIntent().getBundleExtra("data"), false, true);
266+
runNotificationOpenedCallback(appContext.getIntent().getBundleExtra("data"), false);
240267

241268
if (TrackGooglePurchase.CanTrack(appContext))
242269
trackGooglePurchase = new TrackGooglePurchase(appContext);
243270

244271
initDone = true;
272+
273+
// In the future on Android 4.0 (API 14)+ devices use registerActivityLifecycleCallbacks
274+
// instead of requiring developers to call onPause and onResume in each activity.
275+
// Might be able to use registerOnActivityPausedListener in Android 2.3.3 (API 10) to 3.2 (API 13) for backwards compatibility
245276
}
246277

247278
private static void updateRegistrationId(String id) {
@@ -784,7 +815,7 @@ static void sendPurchases(JSONArray purchases, boolean newAsExisting, ResponseHa
784815
}
785816
}
786817

787-
private static void runNotificationOpenedCallback(final Bundle data, final boolean isActive, boolean isUiThread) {
818+
private static void runNotificationOpenedCallback(final Bundle data, final boolean isActive) {
788819
try {
789820
JSONObject customJSON = new JSONObject(data.getString("custom"));
790821

@@ -823,31 +854,43 @@ private static void runNotificationOpenedCallback(final Bundle data, final boole
823854
if (additionalDataJSON.equals(new JSONObject()))
824855
additionalDataJSON = null;
825856

826-
final JSONObject finalAdditionalDataJSON = additionalDataJSON;
827-
Runnable callBack = new Runnable() {
828-
@Override
829-
public void run() {
830-
notificationOpenedHandler.notificationOpened(data.getString("alert"), finalAdditionalDataJSON, isActive);
831-
}
832-
};
857+
if (appContext.isFinishing()
858+
&& (notificationOpenedHandler.getClass().isAnnotationPresent(TiedToCurrentActivity.class)
859+
|| notificationOpenedHandler instanceof Activity )) {
833860

834-
if (isUiThread)
835-
callBack.run();
836-
else
837-
appContext.runOnUiThread(callBack);
861+
// Activity is finished or isFinishing, run callback later when OneSignal.init is called again from anther Activity.
862+
nextInitAdditionalDataJSON = additionalDataJSON;
863+
nextInitMessage = data.getString("alert");
864+
return;
865+
}
866+
867+
fireNotificationOpenedHandler(data.getString("alert"), additionalDataJSON, isActive);
838868
}
839869
} catch (Throwable t) {
840870
Log(LOG_LEVEL.ERROR, "Failed to run callback from notification opened.", t);
841871
}
842872
}
843873

874+
private static void fireNotificationOpenedHandler(final String message, final JSONObject additionalDataJSON, final boolean isActive) {
875+
if (Looper.getMainLooper().getThread() == Thread.currentThread()) // isUIThread
876+
notificationOpenedHandler.notificationOpened(message, additionalDataJSON, isActive);
877+
else {
878+
appContext.runOnUiThread(new Runnable() {
879+
@Override
880+
public void run() {
881+
notificationOpenedHandler.notificationOpened(message, additionalDataJSON, isActive);
882+
}
883+
});
884+
}
885+
}
886+
844887
// Called when receiving GCM message when app is open and in focus.
845888
static void handleNotificationOpened(Bundle data) {
846889
sendNotificationOpened(appContext, data);
847-
runNotificationOpenedCallback(data, true, false);
890+
runNotificationOpenedCallback(data, true);
848891
}
849892

850-
// Called when opening a notification when the app is suspended in the background.
893+
// Called when opening a notification when the app is suspended in the background or when it is dead
851894
public static void handleNotificationOpened(Context inContext, Bundle data) {
852895
sendNotificationOpened(inContext, data);
853896

@@ -885,7 +928,7 @@ public static void handleNotificationOpened(Context inContext, Bundle data) {
885928
}
886929

887930
if (initDone)
888-
runNotificationOpenedCallback(data, false, false);
931+
runNotificationOpenedCallback(data, false);
889932
}
890933

891934
private static void sendNotificationOpened(Context inContext, Bundle data) {

OneSignalSDK/onesignal/src/main/java/com/onesignal/OneSignalUnityProxy.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,14 +131,14 @@ public void idsAvailable(String userId, String registrationId) {
131131

132132
public void enableSound(boolean enable) { OneSignal.enableSound(enable); }
133133

134-
public void enableVibrate(boolean enable) {
135-
OneSignal.enableVibrate(enable);
136-
}
134+
public void enableVibrate(boolean enable) { OneSignal.enableVibrate(enable); }
137135

138136
public void enableNotificationsWhenActive(boolean enable) { OneSignal.enableNotificationsWhenActive(enable); }
139137

140138
public void enableInAppAlertNotification(boolean enable) { OneSignal.enableInAppAlertNotification(enable); }
141139

140+
public void setSubscription(boolean enable) { OneSignal.setSubscription(enable); }
141+
142142
public void postNotification(String json) {
143143
OneSignal.postNotification(json, new PostNotificationResponseHandler() {
144144
@Override

0 commit comments

Comments
 (0)