Continue service when app is killed - android

I have an activity with two buttons (ON and OFF): when I click the ON button a service starts. When I click the OFF botton the service stops. Now, my service does not have problems apart from when I kill the app from "Recent Apps" because in this circumstance the service restarts. I don't want that it restarts but I want that it continues working. The service is a START_STICKY.
This is my "service" code:
#Override
public void onCreate() {
// TODO Auto-generated method stub
myServiceReceiver = new MyServiceReceiver();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
}
public class LocalBinder extends Binder {
SensorService getService() {
return SensorService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (!running){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MY_ACTION_FROMACTIVITY);
registerReceiver(myServiceReceiver, intentFilter);
running = true;
sensorManager=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_NORMAL);
}
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onDestroy() {
Log.v(TAG,"destroy");
// TODO Auto-generated method stub
sensorManager.unregisterListener(this);
mNM.cancel(NOTIFICATION);
this.unregisterReceiver(myServiceReceiver);
super.onDestroy();
}
private void showNotification() {
CharSequence text = getText(R.string.activity);
Notification notification = new Notification(R.drawable.lifestyle, text, System.currentTimeMillis());
SharedPreferences flagNot = getSharedPreferences("flagNotification", 0);
final SharedPreferences.Editor editor = flagNot.edit();
editor.putBoolean("flagNotification",true);
editor.commit();
Intent notificationIntent = new Intent(this, ActivityTab.class);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.app_name),text, contentIntent);
notification.flags |= Notification.FLAG_NO_CLEAR;
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
public void onAccuracyChanged(Sensor sensor,int accuracy){
}
public void onSensorChanged(SensorEvent event){
......
}
public class MyServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int hostCmd = arg1.getIntExtra(CMD, 0);
if(hostCmd == CMD_STOP){
running = false;
stopSelf();
}
}
}
}
Can you help me,please?
Many thanks.

Implement startForeground in your service and send it a persistent notification.
private void startForeground() {
int ID = 1234;
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(getBaseContext());
builder.setContentIntent(pendIntent);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setTicker("CUSTOM MESSAGE");
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(false);
builder.setContentTitle("Test Service");
builder.setContentText("CUSTOM MESSAGE");
Notification notification = builder.build();
startForeground(ID, notification);
}

Related

Montioring sensor values in Android to fire Notifications and then turning the sensor service off

I am trying to monitor the sensor values in Android through a service and if there is any change is the values of the sensor(Accelerometer)....it should fire a Notification and then the service should stop automatically...
But whats happening is that the service doesnot stop and it keeps firing notifications on every movement.
Can anyone suggest a better approach??
Sensor service
public class Sensored extends Service implements SensorEventListener {
SensorManager ssrmgr = null;
Sensor ssr = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
ssrmgr = (SensorManager) getSystemService(SENSOR_SERVICE);
ssr = ssrmgr.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);
ssrmgr.registerListener(this, ssr,SensorManager.SENSOR_DELAY_NORMAL);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float value = event.values[0];
if(value>0)
{
Intent i=new Intent();
i.setClass(this, NotifyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ssrmgr.unregisterListener(this);
stopSelf();
startActivity(i);
}
}
protected void onPause()
{
stopService(new Intent(getApplicationContext(), Sensored.class));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
Notification class
public class NotifyActivity extends ActionBarActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Build notification
// Actions are just fake
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder noti = new NotificationCompat.Builder(this)
.setContentTitle("Inspire Me")
.setSmallIcon(R.drawable.ic_launcher)
.setSound(alarmSound);
noti.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
notificationManager.notify(001, noti.build());
}
}

BroadcastReceiver->Service->Notification

I want to start service in BroadcastReceiver (BOOT_COMPLETED) and make Notification from it.
Like this:
public class AutoLoad extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
Intent i = new Intent(context, MyService.class);
i.putExtra("screen_state", false);
context.startService(i);
}
}
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new
NotificationCompat.Builder(getApplicationContext()).setContentTitle("New mail from ").setContentText("Text")
.setSmallIcon(android.R.drawable.btn_plus).build(); // addAction
NotificationManager nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, notification);
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
But no notification I can see. Please help!
You will need an Activity and run it at least once in order to be able to register to BOOT_COMPLETED intents.

Second Broadcast receiver intent never getting captured in a Service

I am trying to capture the following two broadcasts (android.intent.action.SCREEN_ON & android.intent.action.SCREEN_OFF) from my running foreground service (code below).
Only "android.intent.action.SCREEN_ON" is getting captured.
if(intent.getAction().equals("android.intent.action.SCREEN_OFF")) in onReceive() never gets fired ... neither does myBroadcast_screenoff.
What am I doing wrong here?
(Basic question is how to capture two different intents from a single service)
public class ServiceDataSaver extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
BroadcastReceiver myBroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.SCREEN_ON")) {
Log.v("datasaver", "Screen just turned on");
}
if(intent.getAction().equals("android.intent.action.SCREEN_OFF")) {
Log.v("datasaver", "Screen just turned off");
}
}
};
BroadcastReceiver myBroadcast_screenoff = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.SCREEN_OFF")) {
Log.v("datasaver", "Screen just turned off");
}
}
};
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
IntentFilter filter = new IntentFilter("android.intent.action.SCREEN_ON");
filter.setPriority(999);
registerReceiver(myBroadcast, filter);
IntentFilter filter_screenoff = new IntentFilter("android.intent.action.SCREEN_ON");
filter_screenoff.setPriority(999);
registerReceiver(myBroadcast_screenoff, filter_screenoff);
}
#Override
public void onDestroy() {
super.onDestroy();
// Do not forget to unregister the receiver!!!
//this.unregisterReceiver);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//return super.onStartCommand(intent, flags, startId);
makeServiceForeground(intent);
return START_NOT_STICKY;
}
public void makeServiceForeground(Intent receivedIntent) {
final int myID = 1234;
// The intent to launch when the user clicks the expanded notification
Intent returningintent = new Intent(this, MainActivitySlidingLayer.class);
receivedIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0,
returningintent, 0);
// This constructor is deprecated. Use Notification.Builder instead
Notification notice = new Notification(R.drawable.ic_launcher,
"Facebook is Blocked", System.currentTimeMillis());
// This method is deprecated. Use Notification.Builder instead.
notice.setLatestEventInfo(this, "Facebook is blocked",
"Click here to unblock it ...", pendIntent);
notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);
}
}
Probably just the typo. You're not registering for SCREEN_OFF intent.
In OnCreate()
IntentFilter filter_screenoff = new IntentFilter("android.intent.action.SCREEN_ON");
should be
IntentFilter filter_screenoff = new IntentFilter("android.intent.action.SCREEN_OFF");
and of course you'd better use the constants provided by Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON anyway.

Service Stopping in Android

I have Android Service that runs always in background, and another service which is triggered by the always running service which is alarmmanager service.
Howewer, I want to stop service with a button, my aim is to stop always running service so the alarm manager service will automatically be stopped. Is it correct perspective?
My sample code is as follows
package com.example.deneme;
public class AndroidNotifyService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStartService = (Button)findViewById(R.id.startservice);
Button buttonStopService = (Button)findViewById(R.id.stopservice);
buttonStartService.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(AndroidNotifyService.this, com.example.deneme.AndroidScheduledService.class);
AndroidNotifyService.this.startService(intent);
}});
buttonStopService.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(AndroidScheduledService.ACTION);
intent.putExtra("RQS", AndroidScheduledService.RQS_STOP_SERVICE);
sendBroadcast(intent);
}});
}
}
My always running service
package com.example.deneme;
public class AndroidScheduledService extends Service {
final static String ACTION = "AndroidScheduledServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getBaseContext(),
MyScheduledReceiver.class);
PendingIntent pendingIntent
= PendingIntent.getBroadcast(getBaseContext(),
0, myIntent, 0);
AlarmManager alarmManager
= (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), interval, pendingIntent);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//this.unregisterReceiver(notifyServiceReceiver);
Intent intent = new Intent();
intent.setAction(NotifyService.ACTION);
intent.putExtra("RQS", NotifyService.RQS_STOP_SERVICE);
sendBroadcast(intent);
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
My Alarmmanager service
public class NotifyService extends Service {
final static String ACTION = "NotifyServiceAction";
final static String STOP_SERVICE = "";
final static int RQS_STOP_SERVICE = 1;
HttpClient httpclnt;
HttpPost httppst;
String message;
String response;
//NotifyServiceReceiver notifyServiceReceiver;
private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;
private final String myBlog = "http://android-er.blogspot.com/";
/*
#Override
public void onCreate() {
// TODO Auto-generated method stub
notifyServiceReceiver = new NotifyServiceReceiver();
super.onCreate();
}
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
/*
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION);
registerReceiver(notifyServiceReceiver, intentFilter);
*/
// Send Notification
notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.ic_launcher,
"Notification!",
System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Exercise of Notification!";
String notificationText = "http://www.google.com/";
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent
= PendingIntent.getActivity(getBaseContext(),
0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context,
notificationTitle,
notificationText,
pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
//this.unregisterReceiver(notifyServiceReceiver);
super.onDestroy();
}
/*
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public class NotifyServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int rqs = arg1.getIntExtra("RQS", 0);
if (rqs == RQS_STOP_SERVICE){
stopSelf();
}
}
}*/
}
My BroadCast Receiver Classes
For NotifyService Class
package com.example.deneme;
public class MyScheduledReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(context, com.example.deneme.NotifyService.class);
context.startService(intent2);
}
}
For AndroidScheduledService Class
package com.example.deneme;
public class AutoStartNotifyReceiver extends BroadcastReceiver {
private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){
Intent myIntent = new Intent(context, com.example.deneme.AndroidScheduledService.class);
context.startService(myIntent);
}
}
}
Stopping the service won't stop the Alarm manager service. You have to stop it manually.
Intent intent = new Intent(this, com.example.deneme.AndroidScheduledService.class);
PendingIntent sender = PendingIntent.getBroadcast(this,
0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(sender);
To stop a service:
Intent stopServiceIntent = new Intent(getBaseContext(), yourServiceToStop.class);
getBaseContext().stopService(stopServiceIntent );

Service not being killed via PendingIntent

I have a service that posts a notification, and what I am trying to do is kill that service when the notification is clicked. Here is my code:
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
super.onCreate();
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.ic_launcher,
getResources().getString(R.string.notify_body),
System.currentTimeMillis());
n.setLatestEventInfo(getApplicationContext(),
getResources().getString(R.string.notify_title), getResources()
.getString(R.string.notify_body), PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(
this, StopSelf.class), Intent.FLAG_ACTIVITY_NEW_TASK));
n.defaults = Notification.DEFAULT_ALL;
nm.notify(ID, n);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
nm.cancel(ID);
}
public class StopSelf extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
stopService(new Intent(this, myService.class));
this.finish();
}
}
When I click the notification the statusbar is dismissed, but the notification is still there. Why isn't StopSelf killing the service and calling onDestroy?

Categories

Resources