Skip to content

Commit

Permalink
Merge pull request #115 from caffeinalab/hotfix/android-26-jobservice
Browse files Browse the repository at this point in the history
Fixed notifications not displayed when the app is in background state
  • Loading branch information
Jei authored Nov 26, 2018
2 parents 303a3f6 + ab89be5 commit 6e33ba9
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 23 deletions.
12 changes: 10 additions & 2 deletions android/src/ti/goosh/BroadcastReceiver.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import android.app.Activity;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.TiRHelper;

import com.google.android.gms.gcm.GcmListenerService;
Expand All @@ -29,7 +29,15 @@ public class BroadcastReceiver extends GcmReceiver {
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
IntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Bundle extras = intent.getExtras();
if (extras != null) {
GcmJobService.scheduleJob(context, extras);
}
} else {
startWakefulService(context, (intent.setComponent(comp)));
}
setResultCode(Activity.RESULT_OK);

Log.d(LCAT, "started");
Expand Down
87 changes: 87 additions & 0 deletions android/src/ti/goosh/GcmJobService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package ti.goosh;

import android.annotation.SuppressLint;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.support.annotation.RequiresApi;

import java.lang.ref.WeakReference;

@RequiresApi(api = Build.VERSION_CODES.O)
public class GcmJobService extends JobService {

private static String LCAT = "ti.goosh.GcmJobService";
private static final int JOB_ID = Integer.MAX_VALUE - 4321;

private GcmAsyncTask mAsyncTask;

@RequiresApi(api = Build.VERSION_CODES.O)
static void scheduleJob(Context context, Bundle extras) {
ComponentName jobComponentName = new ComponentName(context.getPackageName(), GcmJobService.class.getName());
JobScheduler mJobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo existingInfo = mJobScheduler.getPendingJob(JOB_ID);
if (existingInfo != null) {
mJobScheduler.cancel(JOB_ID);
}

JobInfo.Builder jobBuilder = new JobInfo.Builder(JOB_ID, jobComponentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setTransientExtras(extras);
int result = mJobScheduler.schedule(jobBuilder.build());
if (result != JobScheduler.RESULT_SUCCESS) {
Log.e(LCAT, "Could not start job, error code: " + result);
}
}

@Override
public boolean onStartJob(JobParameters params) {
mAsyncTask = new GcmAsyncTask(getApplicationContext());
mAsyncTask.execute(params);
return true;
}

@Override
public boolean onStopJob(JobParameters params) {
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
mAsyncTask = null;
}
return false;
}

private class GcmAsyncTask extends AsyncTask<JobParameters, Void, Void> {
private JobParameters params;
private WeakReference<Context> contextRef;

public GcmAsyncTask(Context context) {
contextRef = new WeakReference<>(context);
}

@Override
protected Void doInBackground(JobParameters... params) {
this.params = params[0];

Bundle extras = this.params.getTransientExtras();
try {
new IntentService().handleMessage(contextRef.get(), extras);
} catch (Exception ex) {
Log.e(LCAT, "Exception while handling message: " + ex.getMessage());
}

return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
jobFinished(params, false);
}
};
}
29 changes: 21 additions & 8 deletions android/src/ti/goosh/IntentService.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ public void onMessageReceived(String from, Bundle bundle) {
parseNotification(bundle);
}

public void handleMessage(Context context, Bundle bundle) {
Log.d(LCAT, "Push notification received");
for (String key : bundle.keySet()) {
Object value = bundle.get(key);
Log.d(LCAT, String.format("Notification key : %s => %s (%s)", key, value.toString(), value.getClass().getName()));
}

parseNotification(context, bundle);
}

private int getResource(String type, String name) {
int icon = 0;
if (name != null) {
Expand All @@ -85,18 +95,21 @@ private Bitmap getBitmapFromURL(String src) throws Exception {
}

@TargetApi(26)
private NotificationChannel createOrUpdateDefaultNotificationChannel() {
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
private NotificationChannel createOrUpdateDefaultNotificationChannel(Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String channelName = TiApplication.getInstance().getAppProperties().getString("ti.goosh.defaultChannel", DEFAULT_CHANNEL_NAME);
NotificationChannel channel = new NotificationChannel(DEFAULT_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
return channel;
}

private void parseNotification(Bundle bundle) {
parseNotification(getApplicationContext(), bundle);
}

private void parseNotification(Context context, Bundle bundle) {
TiGooshModule module = TiGooshModule.getModule();

Context context = getApplicationContext();
Boolean appInBackground = !TiApplication.isCurrentActivityInForeground();

// Flag that determine if the message should be broadcasted to TiGooshModule and call the callback
Expand Down Expand Up @@ -169,17 +182,17 @@ private void parseNotification(Bundle bundle) {
if (showNotification) {
Log.w(LCAT, "Show Notification: TRUE");

Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
Intent notificationIntent = new Intent(context, PushHandlerActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra(TiGooshModule.INTENT_EXTRA, jsonData);

PendingIntent contentIntent = PendingIntent.getActivity(this, new Random().nextInt(), notificationIntent, PendingIntent.FLAG_ONE_SHOT);
PendingIntent contentIntent = PendingIntent.getActivity(context, new Random().nextInt(), notificationIntent, PendingIntent.FLAG_ONE_SHOT);

// Start building notification
NotificationCompat.Builder builder = null;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(context, createOrUpdateDefaultNotificationChannel().getId());
builder = new NotificationCompat.Builder(context, createOrUpdateDefaultNotificationChannel(context).getId());
} else {
builder = new NotificationCompat.Builder(context);
}
Expand Down Expand Up @@ -413,14 +426,14 @@ private void parseNotification(Bundle bundle) {
if (idJson.isJsonPrimitive() && idJson.getAsJsonPrimitive().isNumber()) {
id = -1 * Math.abs(idJson.getAsJsonPrimitive().getAsInt());
}
}
}

if (id == 0) {
id = atomic.getAndIncrement();
}

// Send
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(tag, id, builder.build());
} else {
Log.w(LCAT, "Show Notification: FALSE");
Expand Down
3 changes: 1 addition & 2 deletions android/src/ti/goosh/PushHandlerActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import android.os.Bundle;
import android.util.Log;

import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.KrollRuntime;

public class PushHandlerActivity extends Activity {
Expand Down Expand Up @@ -49,5 +48,5 @@ public void onCreate(Bundle savedInstanceState) {
Log.d(LCAT, "resumed");
super.onResume();
}

}
23 changes: 14 additions & 9 deletions android/timodule.xml
Original file line number Diff line number Diff line change
Expand Up @@ -48,20 +48,25 @@
<!-- [END gcm_listener] -->

<!-- [START instanceId_listener] -->
<service
android:name="ti.goosh.InstanceIDListener"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<!-- [END instanceId_listener] -->
<service
android:name="ti.goosh.InstanceIDListener"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<!-- [END instanceId_listener] -->

<service
android:exported="false"
android:name="ti.goosh.GcmJobService"
android:permission="android.permission.BIND_JOB_SERVICE"/>

<service
android:name="ti.goosh.RegistrationIntentService"
android:exported="false">
</service>

<activity
android:name="ti.goosh.PushHandlerActivity"
android:exported="true">
Expand Down
4 changes: 2 additions & 2 deletions example-app/tiapp.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
</ios>
<android xmlns:android="http://schemas.android.com/apk/res/android">
<manifest android:versionCode="1" android:versionName="1.0">
<uses-sdk android:targetSdkVersion="25" android:minSdkVersion="16"/>
<uses-sdk android:targetSdkVersion="26" android:minSdkVersion="16"/>
<supports-screens android:xlargeScreens="false" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true"/>
<application android:hardwareAccelerated="true">
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
Expand All @@ -69,5 +69,5 @@
<target device="iphone">false</target>
<target device="mobileweb">false</target>
</deployment-targets>
<sdk-version>7.0.1.GA</sdk-version>
<sdk-version>7.4.0.GA</sdk-version>
</ti:app>

0 comments on commit 6e33ba9

Please sign in to comment.