How To Run A Code or Full App on Background - java

my App get a Notification when i get time Like Alarm i Just want to Run my app on Background to Can Push my Notification when time come
i was Try to Search about that Problem and ask on Many Android Groups and i Use then a Thread but Nothing work
if (level==100){
Thread T1 = new Thread(new Runnable() {
#Override
public void run() {
// PushNotification Method
PushNotification();
}
});
T1.start();
}
The Code only Run when App Open but When Close the App the Code Not work

If you're trying to receive notifications from GCM, then create a WakefulBroadcastReceiver that can be used to receive the notification and handle it appropriately.
On the other hand, if you're trying to send a normal notification from within your app, then create your own background Service that can be used to send the notification. Here's a link to a similar SO answer that you can use for reference.

Related

react native data only fcm on android: start foreground when app is killed

I'm building a react native app which should handle push notifications.
I'm using react-native-notifications to handle the notification logic, and notifee to show the received notifications. But I have a few problems.
There are 3 'states' in which the app is, when a notification should be handled: app in foreground, background or killed.
When the app is in foreground or in background, I can "catch" the notifications with the event handlers from react-native-notifications and based on the payload, create a notification with notifee to display.
The problem is when the app is killed.
I found a pull request of react-native-notifications (see PR here) that would "read" data-only messages on android when the app is killed.
This works, I console.log the output and it shows up in logcat.
My question now is: how can I create a custom notification with notifee when the app is killed? So no react native code can run?
In my index.js I have the following:
AppRegistry.registerHeadlessTask(
"JSNotifyWhenKilledTask",
() => {
return async (notificationBundle) => {
console.log('[JSNotifyWhenKilledTask] notificationBundle', notificationBundle);
}
}
);
the notification is shown in logcat, but now I want to add notifee to this to create a notification. But then I get the following error (in logcat):
android.app.BackgroundServiceStartNotAllowedException: Not allowed to start service Intent
The code that is a problem is this one:
private void notifyReceivedKilledToJS() {
Bundle bundle = new Bundle(mNotificationProps.asBundle());
Intent service = new Intent(mContext.getApplicationContext(), JSNotifyWhenKilledTask.class);
service.putExtras(bundle);
mContext.getApplicationContext().startService(service);
}
I modified the code to this, but now I get another error:
private void notifyReceivedKilledToJS() {
Bundle bundle = new Bundle(mNotificationProps.asBundle());
Intent service = new Intent(mContext.getApplicationContext(), JSNotifyWhenKilledTask.class);
service.putExtras(bundle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mContext.startForegroundService(new Intent(mContext, JSNotifyWhenKilledTask.class));
} else {
mContext.startService(new Intent(mContext, JSNotifyWhenKilledTask.class));
}
}
android.app.ForegroundServiceStartNotAllowedException: startForegroundService() not allowed due to mAllowStartForeground false
I found this question on SO addressing this problem.
I changed the priority of the notification to "high", and now I get this final error:
android.app.ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() did not then call Service.startForeground():
I'm guessing I should start this Service.startForeground() somewhere in my java code, but I really have no clue where.
Does anyone know a solution on how to "read" a data-only notification on android when the app is killed, and to run some JS code (notifee) to display a notification?
I'm not very good at java btw, any guidance would be welcome.

Close app after some time in background

I'm looking for a way to close an android app after some time while the app has not been in focus. For example if the user open up an other app instead, the app should exit after 5 mins. I have tried using runnable and creating a thread. But those method don't seems to work while the app is in the background (maybe they are pause I'm not sure). So how do I close the app when it is not in focus?
For those who are wonder the reason I want to do this is that the app contains some sensitives data about the user so I want to be sure it is all cleared when they aren't using it.
Something like this might work:
A field inside activity class:
private Thread t = null;
Inside onResume():
if(t!=null) {
if(t.isAlive()) {
t.interrupt();
t.join();
}
t=null;
}
Inside onPause():
t = new Thread() {
public void run() {
try {
sleep(5*60*1000);
// Wipe your valuable data here
System.exit(0);
} catch (InterruptedException e) {
return;
}
}.start();
}
I recommend calling finish() in the onPause() or onStop() callbacks. A TimerTask will not survive onPause() and a Service does not appear, on face value, to give you options. Maybe you can start a service, sleep the thread the service runs on, then kill the processes your app has after the sleep timer expires.
Alternatively, you can just implement some security libraries to help secure the data from other apps.
Here is the Google Services link.
Get the process ID of your application, and kill that process onDestroy() method
#Override
public void onDestroy()
{
super.onDestroy();
int id= android.os.Process.myPid();
android.os.Process.killProcess(id);
}
Refer- how to close/stop running application on background android
Edit- Use this with AlarmManager
The fundamental problem with what you're trying to do is that your Activity may not exist in memory at all when it's "running" in the background. The Android framework may have destroyed the activity instance and even the process it was running in. All that exists may be the persistent state you saved in onSaveInstanceState(...) and a screenshot for the recent apps list. There may be nothing for you to get a reference to and kill.
Frank Brenyah's suggestion to call finish() in onPause() will prevent your activity from running in the background at all, but this is the closest you can get to what you want. You probably only want to do this when isChangingConfigurations() is false. But even when all your app's activities are finished, Android may keep the process and Application instance around to avoid recreating them later. So you may also want to use Bhush_techidiot's suggestion of killing the process. Do this in onPause() because the activity may be destroyed without a call to onDestroy().

Android SignalR should be implemented as Service or IntentService?

On my Android App, I'm implementing SignalR connection (https://github.com/erizet/SignalA) to connect to a Hub server to send requests and receive responses.
a sample of my code is as follows:
signalAConnection = new com.zsoft.SignalA.Connection(Constants.getHubUrl(), this, new LongPollingTransport())
{
#Override
public void OnError(Exception exception)
{
}
#Override
public void OnMessage(String message)
{
}
#Override
public void OnStateChanged(StateBase oldState, StateBase newState)
{
}
};
if (signalAConnection != null)
signalAConnection.Start();
There's also the sending bit
signalAConnection.Send(hubMessageJson, new SendCallback()
{
public void OnError(Exception ex)
{
}
public void OnSent(CharSequence message)
{
}
});
The sending and receiving will occur across activites, and some responses will be sent at random times regardless of the activity, also, the connection should be opened as long as the app is running (even if the app is running in the background) that's why I wish to implement the signalA connection as a background service
The question is should I implement it as:
1 - a Service (http://developer.android.com/reference/android/app/Service.html)
OR
2 - an Intent Service (http://developer.android.com/training/run-background-service/create-service.html)
Keeping in mind that I will need to send strings to the service and get response strings from the service.
I would be most grateful if someone would show me how to implement this kind of connection in code as a background service/intentservice.
Thanks for reading.
UPDATE:
Please see this demo activity made by the developer as how he implemented SignalA
https://github.com/erizet/SignalA/blob/master/Demo/src/com/zsoft/SignalADemo/DemoActivity.java
The problem is AQuery (which I know nothing about) is being used in this demo activity. Does AQuery run in the background all the time ?
The problem is, the latest update on SignalA mentions the following
I have changed the transport. LongPolling now uses basic-http-client
instead of Aquery for http communication. I've removed all
dependencies on Aquery.
Hence I'm not sure whether I should follow this demo activity or not
Update 2:
This is the thing that is confusing me most
in the IntentService, the OnHandleIntent method calls stopSelf after it finishes its tasks, when I actually want the code in the IntentService to keep running all the time
protected abstract void onHandleIntent (Intent intent)
Added in API level 3
This method is invoked on the worker thread with a request to process. Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic. So, if this code takes a long time, it will hold up other requests to the same IntentService, but it will not hold up anything else. When all requests have been handled, the IntentService stops itself, so you should not call stopSelf().
SignalA is running on the thread that creates and starts the connection, but all network access is done in the background. The remaining work on the starting thread is really lightweight, hence its perfectly ok to do it on the UI tread.
To answer your question, you need to have a thread running the signala connection. Therefore I think a Service is the best choice since SignalA need to be running all the time.
Regarding Aquery and the demo project. I removed all dependencies to Aquery in the libraries, not in the Demo. To be clear, you don't need Aquery to run SignalA.
In my case, what I wanted was a Service not an Intent Service, since I wanted something that would keep running until the app closes

Is there a way to run a web browser in Android in background mode? And finalize it?

I'd need to do that for the application I'm building right now, as strange at it would sound, if it could be stopped after some time has passed (let's say a pair of minutes) it would be even better, but if it cannot be done I don't think it's that big of a deal as I guess memory freeing service of Android can take care of this.
Anyway I've tried the following code
final URI uri= URI:parse("http://www.google.com");
new Thread(new Runnable() {
public void run() {
Intent intent=new Intent(Intent.ACTION_VIEW,uri);
context.setActivity(intent);
}
}).start();
And the browser starts but not in the background, it's completely shown, I've tried to exchange ACTION_VIEW for ACTION_USER_BACKGROUND, but with that the application fails.
Any idea? Thanks for your help.

Architecture for simple timer app

I am currently working on a very simple countdown timer app. I need some advice on the correct architecture for a timer which can both fire when the app is closed but also show the progress when the app is open.
What I had until now is a simple Handler which executes a Runnable every 100 ms to update the progress bar and call the handler again like this
// ...
// start the timer
tickHandler.postDelayed(runnable, 100);
// ...
private Handler tickHandler = new Handler();
private Runnable runnable = new Runnable(){
#Override
public void run() {
if(tick()){
tickHandler.postDelayed(this, 100);
}
}
};
Now I wanted to be able to have the Timer running even when the app is closed. I first thought about a Service but then discovered the AlarmManager class which seams to do the job and is much easier to use. However I not only want to be able to post a notification to the notification center but also want the app opened up again and showing that the timer has finished.
Can this be done with the AlarmManager or do I need to implement a Service? How would the architecture for this application look like in terms of where is the control passed from the Activity to the Service and more importantly back again?
Thanks for any hints!
I guess, the AlarmManager does exactly what you want:
Taken from Android AlarmManager
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
So you can register the Intent, which you want to start after the Timer has finished and show the user that the Timer has stopped. Therefore, the AlarmManager should do the trick!
Btw: Using a Service may also work but brings other implications. For example, your app would have to be started during boot phase, which would disable it to be installed on external storage. See Android Install Locations

Categories