Launch an app from notification - android

I am building an application using PhoneGap, which revolves around a timer I have created. I am struggling at the moment as I need a way of having the app open itself if the timer reaches zero. I have currently put in place a notification for when the timer runs out, and the user can launch the app from there. However I need a way of launching the app if the user "misses" the notification or something similar.
For example, when the timer on the local "timer" app on a mobile device runs out, it will open itself to notify the user that the time has ran out.
Any suggestion would be appreciated,
Thanks.

Just write the code for opening the launcher Activity instead of showing notification in your service class.When the timer runs out the launcher activity will start instead of notification.
the code will look similar to this:
public class AlarmService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//calling Launcher Activity
Intent alarmIntent = new Intent(getBaseContext(), AlarmScreen.class);
alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
alarmIntent.putExtras(intent);
getApplication().startActivity(LauncherActivity.class);
AlarmManagerHelper.setAlarms(this);
return super.onStartCommand(intent, flags, startId);
}
}
I hope you are satisfied with this answer.

Related

Never ending android background server connection

I have an android app and a server application written in Java. I basically want the app to connect to the server every few seconds to get the newest information, and if neccessary display a push notification, like a Messenger App. I'm new to this, and I've tried multiple ways, but nothing of what I tried seems to work.
I've used a Service which connects to the server every X seconds and gets the newest information from it. The service restarts when It gets destroyed, so it even runs in the background when the app is terminated, but after a while it just stops working and doesn't restart with the error message Not allowed to start service Intent {snip}: app is in background. I have no idea if this approach is even a good idea, and I've tried some other things too, but I don't get anywhere, so any advice on how an application like this should be done would be really helpful!
This is my Service class:
public int counter=0;
public ConnectionService(Context applicationContext) {
super();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Intent broadcastIntent = new Intent(this, BootBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
stoptimertask();
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 1000, 1000); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
counter++;
ConnectionManager.oneWayCall(new DebugPacket("Debug Packet: " + counter));
}
};
}
I don't neccessarily need help with this exact code, if apps like these should be done in a completely different way, please point me into the right direction.
now you can not run services in background forever . system will terminate it after sometime even if you use foreground service.
instead of fetching data every x seconds i would recommend ask your backend guy to send data in fcm notification if data is not large.
if you can wait for 15 minutes for fetching new data you can use workmanager.
there is one ugly way of keeping services alive for longer time i will suggest not to use it .
you can start service every x seconds when you receive notification your app is considered in foreground when you receive notification in this window you can start service. catch is you have to send notifications every x seconds.

Can't get my android service working if my app closes

Hi guys I'm facing this problem with no success in tests, I have been looking for info but can't find any solution at the moment. I followed the guide for services, and did all the guide says, but am still having issues.
My code for the service:
[Service(Label="MyService")]
public class MyService : Service{
protected override StartCommandResult onStartCommand(Intent intent, StartCommandFlags flags, int startId){
var t = new Task(() => {
Looper.prepare();
do{
DoServiceWork();
while(running);
});
t.Start();
return StartCommandResult.Sticky;
}
}
And in my main activity:
protected override void OnCreate(Bundle bundle){
new Task(StartService).Start();
}
void StartService(){
var intent = new Intent(Application.Context, typeof(MyService));
Application.Context.StartService(intent);
}
I can't get my service continue working when my app is killed, I hope you guys can help me with this, thanks in advance for those that can help me.
I can't get my service continue working when my app is killed
Please refer to this, in this article, you can find this:
Note that services, like other application objects, run in the main thread of their hosting process.
"Service run in the main thread", that means if your app/main-process/main-thread has been killed, your service will been killed. If you want your service to run, your app must be alive. No custom Service can always run.
You can use IntentService to do heavyweight calculation, and at the same time, it will improve the priority of your app so that your app can't been killed.

Application starts new service when app is closed

I have an android app with service that has to track user's location even with closed application only if user set flag in app. So I start service in code after user clicks button and stop when he clicks it again with following code
alarm.changeAlarmStatus();
if(alarm.getAlarmStatus()) {
SharedPreferences.Editor ed = alarmPreferences.edit();
ed.putFloat("MARKER_LATITUDE", (float) theMarker.getPosition().latitude);
ed.putFloat("MARKER_LONGITUDE", (float) theMarker.getPosition().longitude);
ed.commit();
startService(myIntent);
}
else{
stopService(myIntent);
}
It seems to work fine. Service works and does what it should. But problem is if I close application through the task manager I see in logcat that Service starts again(but only if service is already working) and it causes nullPointerException because intent is null. You can see in this code why it happens
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Bundle bundle = intent.getExtras();
alarm = (Alarm) bundle.getSerializable("alarm");
Log.d("service","On Start Command is called ");
serviceIntent = intent;
return START_STICKY;
}
However I need to start my service only by pressing button and no other way. Does anyone know how to fix that?
Return START_NOT_STICKY in onStartCommand instead of START_STICKY.
If START_STICKY is returned, system will try to re-create service after it is killed.
If START_NOT_STICKY is returned, system will not try to re-create service after it is killed.

Send HTTP GET Request After X Seconds, Service Gets Killed

The title may seem duplicate but the question not about how to make the request, im sending a HTTP Get request from my android application to a web server after a specified interval using a service, the problem is it is stopped after i perform any other action on the device like play a video. The service looks like
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Context ctx=this;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//perform GET here
}, 0, 5000);
return Service.START_STICKY;
}
any idea why such behaviour im experiencing even though im returning the Service.START_STICKY
Regards.
As mentioned in comment you can take the approach of PendingIntents and BroadcastReceiver in which you can leave a pending intent at specified time and register a receiver and in onreceive you can perform you operation whether to start service or hit a werbservice.
Please go through http://code.tutsplus.com/tutorials/android-fundamentals-scheduling-recurring-tasks--mobile-5788
also http://www.sitepoint.com/scheduling-background-tasks-android/ for better understanding
Try running your service in the 'foreground'. This way it is less likely to get killed.
Check out: http://developer.android.com/guide/components/services.html#Foreground

Android: Re-invoke application if task manager kill

Application thread get close if its killed by task manager. Need to re-invoke application as though its killed by other application or task manager. Any idea?
You have to run background service with START_STICKY command.
Just extends Service and override onCommand like this :
#Override
public int onStartCommand(Intent intent,int flags,int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
Like this your Service is restart when it's close (by system or anything else)
You just have now check on your service (onCreate for example) if application is running or not and launch it again if not. I suppose PackageManager let you check this or simply put a static boolean is_alive to see if your activity is always running.
Regards
Jim
Bug in Android 2.3 with START_STICKY
I needed to keep alive a Service with all my forces. If the service is running anytime you can pop the UI.
onDestroy()
it will re-launch.
Can't be uninstalled the app, because it has a Device Administrator.
It is a kind of parental control, the user knows it is there.
Only way to stop is to remove the Device Admin, and uninstall it, but removing Device Admin will lock the phone as Kaspersky how it does.
There are a loot of braodcast receivers, such as boot finshed, user presen, screen on, screen off... , many other, all starting the service, you can do it with UI too. Or in the service check if your activity alive , visible, if not, than pop it.
I hope you will use with good reason the info!
Edit: Restart service code snippet:
// restart service:
Context context = getApplicationContext();
Intent myService = new Intent(context, MyService.class);
context.startService(myService);
Edit2: add spippet to check if the service is running in ... a load of Broadcasts
public static boolean isMyServiceRunning(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
Log.d("myTag", "true");
return true;
}
}
Log.d("myTag", "false");
return false;
}
Edit3 other service start:
public static void startTheService(Context context) {
Intent myService = new Intent(context, MyService.class);
context.startService(myService);
}
Dont't forget Android 2.3 bug: do the logic for initialization in
#Override
public void onCreate()
and not in:
#Override
public int onStartCommand(Intent intent, int flags, int startId)
While look at Google IO official product source code I have found the following
((AlarmManager) context.getSystemService(ALARM_SERVICE))
.set(
AlarmManager.RTC,
System.currentTimeMillis() + jitterMillis,
PendingIntent.getBroadcast(
context,
0,
new Intent(context, TriggerSyncReceiver.class),
PendingIntent.FLAG_CANCEL_CURRENT));
URL for code
You can start a sticky service and register an alarm manager that will check again and again that is your application is alive if not then it will run it.
You can also make a receiver and register it for <action android:name="android.intent.action.BOOT_COMPLETED" /> then you can start your service from your receiver. I think there should be some broadcast message when OS or kills some service/application.
Just to give you a rough idea I have done this and its working
1) register receiver
Receiver Code:
#Override
public void onReceive(Context context, Intent intent) {
try {
this.mContext = context;
startService(intent.getAction());
uploadOnWifiConnected(intent);
} catch (Exception ex) {
Logger.logException(ex);
Console.showToastDelegate(mContext, R.string.msg_service_starup_failure, Toast.LENGTH_LONG);
}
}
private void startService(final String action) {
if (action.equalsIgnoreCase(ACTION_BOOT)) {
Util.startServiceSpawnProcessSingelton(mContext, mConnection);
} else if (action.equalsIgnoreCase(ACTION_SHUTDOWN)) {
}
}
Service Code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Logger.logInfo("Service Started onStartCommand");
return Service.START_STICKY;
}
I prefer doing nothing in onStartCommand because it will get called each time you start service but onCreate is only called 1st time service is started, so I do most of the code in onCreate, that way I don't really care about weather service is already running or not.
according to #RetoMeyer from Google, the solution is to make the app "sticky".
for this, you must establisH START_STICKY in your intent service management.
check this reference from developer android
Yes, Once memory low issue comes android os starts killing application to compensate the required memory. Using services you can achieve this, your service should run parallely with your application but see, some of the cases even your service will be also killed at the same time. After killing if memory is sufficient android os itself try to restart the application not in all the cases. Finally there is no hard and fast rule to re-invoke your application once killed by os in all the cases it depends on os and internal behaviours.

Categories

Resources