I have a question whereby how to let the app run actively behind the background despite the app is not being open by the user.
Taking for example, I want to receive notification or run a section of code despite the application is not open or active.
I have a question whereby how to let the app run actively behind the background despite the app is not being open by the user.
Taking for example, I want to receive notification or run a section of code despite the application is not open or active.
To handle notification while your app is closed, opened or in background, you can create a service extending
com.google.firebase.messaging.FirebaseMessagingService
public class YourMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
// Handle your notification here ...
// Parse the notification, create your app channel,
// set the activity to run when clicking the notification, ...
}
}
You need to declare your service in your app's AndroidManifest.xml file:
<service android:name=".YourMessagingService ">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
You can look at these pages for more infos: https://firebase.google.com/docs/cloud-messaging/android/receive
Cannot find method createNotificationChannel(NotificationChannel)
To run any code in the background you need to create a service class, when your app goes into background start that service using "startService()" method, but you need also to create a notification telling the user that the app is running a service so the system will not kill your service. this is the notification :
Notification.Builder builder = new Notification.Builder(this)
.setContentTitle("Title")
.setContentText("content");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
builder.setChannelId(channelId)
//Make this notification ongoing so it can’t be dismissed by the user//
.setOngoing(true)
.setSmallIcon(R.drawable.notification_icon);
startForeground(id, builder.build());
and inside the service class's onCreate write your logic. hope this helps