I am trying to add push notifications to my android app. Currently the min sdk version is 22 and the target version is 26. Push notifications work when using an api before 26, but when running on api 26(Oreo) no notifications show up.
Research has told me that I need to use the new constructor NotificationCompat.Builder(Context, ChannelID)
, but I only have the depracated option available and can not seem to figure out how to use the new version. How can I get this new constructor while also allowing my app to be compatible with older api version?
private void sendNotification(String title, String messageBody, String clickAction) {
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);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setChannel(channelId)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1 /* ID of notification */, notificationBuilder.build());
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.ventech.tempmonitor"
minSdkVersion 22
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.sun.jersey:jersey-core:1.19.4'
compile 'com.android.support:design:26.+'
compile 'com.androidplot:androidplot-core:1.5.1'
compile 'com.google.code.gson:gson:2.8.1'
compile 'com.google.firebase:firebase-messaging:10.0.1'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'