continuously background service in react native - react-native

I have an app that get notification from signal R.In foreground I dont have problem and it works.When the app is in background I want to have background service that always listen to signal R notification.(Signal R notifications fail if the user is offline). Packages in react native dont do it .I try with Headless but it does not work properly.
This is my service.
enter code here public class Service extends HeadlessJsTaskService {
#Nullable
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"service",
Arguments.fromBundle(extras),
5000);
}
return null;
}
}
And in MainApplication inside create method i call it.
enter code here Intent serviceIntent = new Intent(context, com.Myservice.Service.class);
serviceIntent.putExtra("hasInternet", hasInternet);
context.startService(serviceIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);

Related

Firebase push notification is not generated when app is killed in android?

Sorry for bad english!!!
I am developing my final year project where i need a chat box. i have successfully develop the chat system. but there is little bit of problem with notification. When my app is running on device it receives all the notifications but after killing or closing the application no notification arrived on y device. i have tested it on many devices but all in vain. Please help on this because i have to submit this on next monday.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() {
}
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if(remoteMessage.getNotification()!=null){
String title=remoteMessage.getNotification().getTitle();
String body=remoteMessage.getNotification().getBody();
NotificationHelper.displayNotification(getApplicationContext(),title,body);
}
}
}
public class NotificationHelper {
public static void displayNotification(Context context,String title,String body){
Intent intent=new Intent(context,ChatActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(
context,
100,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(context, ChatActivity.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notifications)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManagerCompat=NotificationManagerCompat.from(context);
notificationManagerCompat.notify(1,mBuilder.build());
}
}

Background service not working App crashes in android 8.0.1

This is my receiver class
public class LocationAlarmReceiver extends BroadcastReceiver {
private static final String TAG = "LocationAlarmReceiver";
#Override
public void onReceive(Context context, Intent intent) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (AppClass.networkConnectivity.isNetworkAvailable()) {
if (AppClass.isUserLoggedIn()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, UpdateLatLngBackgroundService.class));
} else {
context.startService(new Intent(context, UpdateLatLngBackgroundService.class));
}
}
}
}
}
}
Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification:
Exception is coming
If you are starting a background service as by using startForegroundService
it will be consider as a Foreground service. For Foreground service you have to create a notification to display. see for more detiails
And while creating notification from oreo(8.0) onwards you have to create a channel and register with NotificationManager. More details how to create notification channel
make sure that you added attribute -> name=".the name of the class that you created channels in"
inside tag in manifest file.

How to call a pushNotification only when the application is in sleep mode from portable project

I am using a CrossPlateForm technique to Create Android and IOS app using xamarine, i want to send push notification when my application is in sleep mode,
this is my method
public void pushNotifications(int count)
{
Notification.Builder builder = new Notification.Builder(this)
.SetContentTitle("new Messages")
.SetContentText("Hello World! This is my first notification!")
.SetSmallIcon(Resource.Drawable.icon);
// Instantiate the Inbox style:
Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
// Set the title and text of the notification:
builder.SetContentTitle(count+" new messages");
//builder.SetContentText("chimchim#xamarin.com");
// Plug this style into the builder:
builder.SetStyle(inboxStyle);
// Build the notification:
Notification notification = builder.Build();
// Get the notification manager:
NotificationManager notificationManager =
GetSystemService(Context.NotificationService) as NotificationManager;
// Publish the notification:
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);
}
the count will come from a service which i wrote in portable project, when i tried to write pushNotification method in portable project Notification.Builder i cannot access Notification namespace. I want to trigger a method in portable project whenever applications to sleepmode and show the count using pushNotification, or is their any alternative way to do this?
You should try call your method on App.cs inside the OnSleep function:
public class App : Application
{
{
...
}
protected override void OnSleep ()
{
// Your method here
}

Start Activity with UI updated from notification if service running

I'm making kind-of an audio player. Currently I have a MediaPlayer running in the Activity itself (which I know is bad). There is a SeekBar on the screen which gets updated as the music plays, like so:
private Runnable mUpdateTimeTask = new Runnable() {
public void run()
{
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
songTotalDurationLabel.setText("" + utils.millisecondsToTimer(totalDuration));
songCurrentDurationLabel.setText("" + utils.millisecondsToTimer(currentDuration));
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
songProgressBar.setProgress(progress);
if(mp.isPlaying())
mHandler.postDelayed(this, 100);
else
mHandler.removeCallbacks(mUpdateTimeTask);
}
};
Once the user presses the back button or kills it from the recent apps list, the music stops.
Now I want the music to run in the background, so looking around the internet I found to run it in a Service, and calling startService() from Activity. Also I have a notification come up when music is playing and removed when it is paused.
I understand from a service I'll get the music to play even when app gets closed. But what I didn't understand is, if the user taps on the notification given the service is running, the activity restarts with the SeekBar at progress = 0.
How do I get the UI to update the SeekBar to the correct value from the Service after the activity restarts?
Figured it out!
The solution is to get the running services using the ActivityManager and find your service like this
private boolean fooRunning()
{
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if("com.name.packagename.foo".equals(service.service.getClassName()))
{
return true;
}
}
return false;
}
If this method returns true, bind to the service and get the current position from the MediaPlayer object
public void bindToService()
{
if(fooRunning())
{
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
serviceExists = true;
}
else
serviceExists = false;
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder serviceBinder)
{
bar binder = (bar) serviceBinder;
mService = binder.getService();
if(serviceExists)
{
int getProgress = mService.mp.getCurrentPosition();
// mp is the MediaPlayer object in the service
seekbar.setProgress(getProgress);
}
}
#Override
public void onServiceDisconnected(ComponentName className)
{
}
};
The Service class is like this:
public class foo extends Service
{
private MediaPlayer mp = new MediaPlayer();
private final IBinder mBinder = new bar();
public class bar extends Binder
{
public foo getService()
{
return foo.this;
}
}
#Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
}
Hope this helps someone!

How to display Service text updates on Screen in Android?

I am creating an Android activity and starting a service from this activity using the following code. Now I want to display text "Hello user" from this service to screen, meaning service should trigger this display. I could use Toast.maketext.show but the display will disappear after couple of seconds.
new Thread(new Runnable() {
#Override
public void run() {
startAdapterIntent.setAction("START_ADAPTER");
startService(startAdapterIntent);
System.out.println("Thread2: Adapter Service started.");
}
}).start();
How do I do that?
I tried to use this link:
Making changes to Main Activity UI from thread in Service
and its (probably) parent link
http://developer.android.com/reference/android/app/Service.html
section "Remote Messenger Service Sample"
While using this second link, the onServiceConnected part of ServiceConnection doesn't seem to be working? Please help. Thank you.
From within your service you should create a handler that can be triggered by a timer task, the handler should be the one directly responsible of doing the communication with the currently active UI thread..an example would be
long delay = 3000;
long period = 3000;
TimerTask mDoTask = new TimerTask() {
#Override
public void run() {
xHandler.sendMessage(Message.obtain(xHandler, SOME_OPERATION));
}
};
mT.scheduleAtFixedRate(mDoTask, delay, period);
Handler xHandler=new Handler(){
#Override
public void handleMessage(Message message){
switch (message.what){
case SOME_OPERATION:
YourMethod();// in this method you can display your text
break;
}
}
};