How to cold start a React Native app over device lock screen? - java

I'm building a VoIP app on React Native, which detects incoming calls using push notifications. I need to start the app and bring it to the foreground on receiving a push notification. I'm able to achieve that for the following scenarios:
When the device is unlocked and:
The app is minimized (is still in the background)
The app is not in the background (killed from multitasking view)
When the device is locked and:
The app is minimized (is still in the background)
The only scenario I'm not able to handle is when the device is locked and the app is killed. The app starts but does not show up over the lock screen. Instead, the user needs to unlock the phone to access the app.
Here's the piece of code that runs when a notification is received,
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent notificationIntent = new Intent(this, MainActivity.class);
// Check if app is running
if(MainActivity.isAppRunning) {
startActivity(notificationIntent);
Intent messagingEvent = new Intent(MESSAGE_EVENT);
messagingEvent.putExtra("message", remoteMessage);
// Broadcast it so it is only available to the RN Application
LocalBroadcastManager
.getInstance(this)
.sendBroadcast(messagingEvent);
} else {
startActivity(notificationIntent);
try {
// If the app is in the background we send it to the Headless JS Service
Intent headlessIntent = new Intent(
this.getApplicationContext(),
BackgroundListenService.class
);
headlessIntent.putExtra("message", remoteMessage);
this
.getApplicationContext()
.startService(headlessIntent);
Log.d(TAG, "message: " + remoteMessage);
HeadlessJsTaskService.acquireWakeLockNow(this.getApplicationContext());
} catch (IllegalStateException ex) {
Log.e(
TAG,
"Background messages will only work if the message priority is set to 'high'",
ex
);
}
}
}
And here's my MainActivity:
public class MainActivity extends NavigationActivity {
public static boolean isAppRunning;
private static boolean isMessageRecieved;
private class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
isMessageRecieved=true;
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this);
super.onCreate(savedInstanceState);
isAppRunning = true;
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
// Subscribe to message events
localBroadcastManager.registerReceiver(
new MainActivity.MessageReceiver(),
new IntentFilter(MyFirebaseMessagingService.MESSAGE_EVENT)
);
if(isMessageRecieved) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
window.clearFlags(WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = "1";
String channel2 = "2";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1",NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
isAppRunning = false;
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
}

Related

How to know os kill my foreground service android

I made a lock screen app. I want to restart my service when the OS kills the service in Xiaomi Redmi Note 10 Pro (MIUI 12). When the service is killed, onDestroy is not call.
public class LockScreenService extends Service {
SharedPreferences prefs;
private BroadcastReceiver screenStateReceiver;
public static boolean isScreenReceiverRegistered=false;
public IBinder onBind(Intent paramIntent) {
return null;
}
public void onCreate() {
super.onCreate();
prefs = getSharedPreferences("SettingPreference", Context.MODE_PRIVATE);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.setPriority(999);
screenStateReceiver = new ScreenStateReceiver();
registerReceiver(screenStateReceiver, filter);
isScreenReceiverRegistered = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = createNotificationChannel(notificationManager);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.icon_notification)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.build();
startForeground(127, notification);
}
}
#RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager){
String channelId = "my_service_channelid";
String channelName = "Lock Screen Running";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
// omitted the LED color
channel.setImportance(NotificationManager.IMPORTANCE_NONE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(channel);
return channelId;
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return START_STICKY;
}
and on onDestroy() function I restart my service.
Manifests
<service android:name=".LockScreenService"
android:process=":ServiceProcess"
android:enabled="true"
android:exported="false"/>
try this, if you want to get it in onResume()
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: GamePreferences.getPid()--------> " + GamePreferences.getPid());
Log.d(TAG, "onResume: android.os.Process.myPid()--------> " + android.os.Process.myPid());
if (GamePreferences.getPid() != 0) {
if (GamePreferences.getPid() != android.os.Process.myPid()) {
Log.d(TAG, "GamePreferences.getPid() != android.os.Process.myPid(): --------> " + android.os.Process.myPid());
//restart your service in foreground
return;
}
}
}
According to the documentation, there is no guarantee onDestroy will be called. I could not find an explicit mention to what happens when the process is killed, but it seems that you are more likely to be called onStop. So you can try to start your service with an intent from onStop.
Also, there are documented ways to prevent your process to be elected, such as: having a related Activity running or having ongoing callbacks in BroadcastReceiver or Service.
Note well that your process might get killed by the user, and refusing to comply to the user's desire to kill is invasive. Therefore the best solution should be designed around the actual reason why a user would want your process to stay alive.

Is there a way to make my foreground service run without stopping. It stops when phone cache is cleared by Cross(X) button in minimize window?

I have made a foreground service and it runs non-stop but stops only when the phone cache is cleared (Clicking on Cross(X) button in the Recent Apps window ). Is there a way I can run it non-stop even after clearing the recent apps? And yes, there are other applications which run non-stop in this situation also, like Google Music.
I have tried overriding the Service onDestroy(), onTrimMemory(), dump() methods.
public class MyForeGroundService extends Service {
String CHANNEL_ID = "My Service";
#Override
public void onCreate() {
createNotificationChannel();
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Title")
.setContentText("Content Text")
.setPriority(NotificationCompat.PRIORITY_MAX)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Audio Capture Started !", Toast.LENGTH_LONG).show();
return START_REDELIVER_INTENT;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
Log.i(TAG, "createNotificationChannel()");
}
#Override
public void onDestroy() {
startService(new Intent(getApplicationContext(), MyForeGroundService.class));
Intent intent = new Intent(getApplicationContext(), MyForeGroundService.class);
sendBroadcast(intent);
Toast.makeText(getApplicationContext(), "Service Killed!!!", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent intent = new Intent(getApplicationContext(), MyForeGroundService.class);
startService(intent);
}
#Override
public void onTrimMemory(int level) {
startService(new Intent(getApplicationContext(), MyForeGroundService.class););
}
#Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
startService(new Intent(getApplicationContext(), MyForeGroundService.class););
}
But stops only when the phone cache is cleared (Clicking on Cross(X)
button in the Recent Apps window )
You mean when the app removed from recent apps.
There are other application which run non-stop in this situation also.
They using their own hacks.
Is there a way to make my foreground service run without stopping?
No, you should have your own implementation to do so.

Android Service stops broadcasting progress after a while

I have an Activity where the user can download a video. Upon user's click, the Download Service starts to download the content.
There is a progress bar in the Activity UI which I would like to update according to download progress in the service which broadcasts the progress periodically.
Everything works fine but after a certain time the service stops sending any broadcast progress, hence, the UI does not update anymore.
Additionally, how I can resume receiving the progress broadcast when the user goes to another Activity and comes back to this Activity? I mean, even if the above issue is solved, when the user presses back button and go to other activity and comes back to this activity, the progress gets lots. How can I check for any existing broadcast and receive it whenever the user comes to this activity.
In the ACTIVITY:
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Log.d("DownloadService", "Progress Received In Activity");
Double progress = bundle.getDouble("PROGRESS");
updateDownloadProgressBar(progress);
}
}
};
private void startDownloadService() {
final String videoId = mItem.getAttributes().get(KEY_ASSET_ID);
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("VIDEOID", videoId);
startService(intent);
}
in the onResume():
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION_SERVICE));
in the onPause():
unregisterReceiver(receiver);
In the SERVICE:
private void publishProgress(double progress) {
Log.d(TAG, "Broadcasting progress from Service");
Intent intent = new Intent(NOTIFICATION_SERVICE);
intent.putExtra("PROGRESS", progress);
sendBroadcast(intent);
}
The download and progress work fine to 38% then stop.
It seems that the service is being stopped/killed from the OS, to avoid that use foreground service so you can make sure it will not be killed from the OS.
See the sample code below:
Service
public class PendingService extends Service {
private final static String TAG = "PendingService";
public final static int NOTIFICATION_ID = 94;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startInForeground();
// Do your work here ...
return START_STICKY;
}
private void startInForeground() {
String NOTIFICATION_CHANNEL_ID = "default";
String NOTIFICATION_CHANNEL_NAME = "My Pending Service";
String NOTIFICATION_CHANNEL_DESC = "This notification holding a pending task";
Intent notificationIntent = new Intent(this, SplashActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.notification)
.setOngoing(true)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
channel.setDescription(NOTIFICATION_CHANNEL_DESC);
channel.setSound(null, null);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
Notification notification = builder.build();
startForeground(NOTIFICATION_ID, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
removeNotification(NOTIFICATION_ID);
// ....
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void removeNotification(int notificationId) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(notificationId);
}
}
}
Utils you may need
class ServiceUtils {
/**
* #param service: Service to run
*/
fun startService(context: Context, service: Class<out Service>) {
val serviceIntent = Intent(context, service)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent)
} else {
context.startService(serviceIntent)
}
}
/**
* #return True: if the service is running
*/
fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
}

Why does foreground service stop working when device go into sleep mode

I want to create an app that is constantly checking for location change and put the current location in the firebase (e.g. an app for runners).
Unfortunately the foregroundservice is being stopped or paused every time the device go into sleep mode.
For starters I wanted to create a foreground service that is continuously writing information to the base (that would be a time stamp or a simple string) every second.
After some time it just stops writing to firebase without calling stopself().
The service is working fine on the emulator (even if put to sleep), but stops when tested on a real device – in my case Huawei, Android 8.1.0.
What should I do to force service to run in every state of the device?
My MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", "start");
startForegroundService(intent);
}
else {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", "start");
startService(intent);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", "stop");
startForegroundService(intent);
}
else {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", "stop");
startService(intent);
}
}
}
MyService:
public class MyService extends Service {
int i =0;
private String CHANNEL_ID = "2345";
#Override
public void onCreate() {
super.onCreate();
}
public MyService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(1000, createNotification());
String action = intent.getExtras().getString("action");
switch (action){
case "start":
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
myfunction();
handler.postDelayed(this, 1000);
}
};
break;
case "stop":
stopfunction();
break;
}
handler.postDelayed(runnable, 1000);
return START_NOT_STICKY;
}
private void stopfunction() {
stopSelf();
}
private void myfunction() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("locations");
myRef.child("location").setValue(i);
i++;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
#RequiresApi(Build.VERSION_CODES.O)
private void createChannel(){
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.infoTxt),
NotificationManager.IMPORTANCE_HIGH);
channel.setShowBadge(false);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(channel);
}
private Notification createNotification(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
createChannel();
}
Intent notificationItent = new Intent(this, MainActivity.class);
notificationItent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, 0, notificationItent, 0);
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setColor(ContextCompat.getColor(this, android.R.color.background_dark))
.setContentIntent(intent)
.setSmallIcon(R.drawable.ic_launcher_background)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setContentTitle("GPS Location")
.build();
}
}
I've tried everything: service, foreground service, broadcast receiver, jobSheduler, WorkerManager – nothing helped. Then I found it’s a new HUAWEI feature called “power-intensive app monitor “. It kills every app that runs in the background for a long time unless user gives special permissions to it.
The path to do this:
Settings -> Security & privacy -> Location services -> recent location requests: YOUR APP NAME -> Battery -> uncheck Power-intensive prompt, App launch: Manage manually: check all three positions: Auto-launch, secondary launch, run in background.
I don’t know is there a way to do this programmatically. I think the best way is to create a sort of help activity and explain the user what to do if application won’t work.
Foreground services generally should be used for task which require user attention such as visual processes.
use Background service instead

Run API every second in Background after Android App is killed in Oreo version

I am trying to Build a Android Application which will run every second and when app is closed or killed then also it should run continuously in Background.
When API response condition is satisfied it should show a Local Notification..
I have used Service Class for background Task. It was working fine in all version Except the Oreo Version (8.1v)
I have check website and Example related to it, I have find out that we can't perform background task in Oreo Version after the app is closed or killed.
So I tried to use startForeground() then also it is not working,
After many tries, finally I am asking this question here.
So please help me to run a API in Background when App is closed.
MainActivty.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(this, new Intent(this,MyService.class));
} else {
startService(new Intent(this,MyService.class));
}
}
MyService.class
public class MyService extends Service {
public static final int notify = 3000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
new ApiCallAsyncTask().execute(URL);
}
});
}
}
}
Notification Method which is called in ApiCallAsyncTask class
Notification notif;
#TargetApi(Build.VERSION_CODES.O)
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void notification(String Name, String time,String mId,int id){
Intent intent = new Intent(MyService.this, MainActivity.class);
String CHANNEL_ID = String.valueOf(id);
PendingIntent pendingIntent = PendingIntent.getActivity(MyService.this, 100, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, Name, NotificationManager.IMPORTANCE_DEFAULT);
notif = new Notification.Builder(MyService.this)
.setContentIntent(pendingIntent)
.setContentTitle("Reminder")
.setContentText("hello")
.setSmallIcon(R.drawable.logo)
.setOnlyAlertOnce(true)
.setColor(ContextCompat.getColor(MyService.this, R.color.colorPrimaryDark))
.setChannelId(CHANNEL_ID)
.build();
notificationManager.createNotificationChannel(mChannel);
}else {
notif = new Notification.Builder(MyService.this)
.setContentIntent(pendingIntent)
.setContentTitle("Reminder")
.setContentText("hello")
.setSmallIcon(R.drawable.logo)
.setOnlyAlertOnce(true)
.setColor(ContextCompat.getColor(MyService.this, R.color.colorPrimaryDark))
.build();
}
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notif);
startForeground(1, notif);
}
Thank You..
You can use combination of JobIntentService + AlarmManager(for scheduling) or JobScheduler API.
But I strongly recommend replace your approach with Firebase Cloud Messaging. So you will place business logic on server side and notify clients in special cases.

Categories