Second Broadcast receiver intent never getting captured in a Service - android

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.

Related

Broadcast receiver is not working when app on foreground or active

I am building app regarding battery indicator and i am using code from this post.
Getting battery status even when the application is closed
it is working fine when app is closed, but when an app is active or on foreground it did not work or did not send any broadcast.
This is main activity from i start service
public class Main extends Activity {
private MyService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (service == null) {
Intent i = new Intent(this, MyService.class);
startService(i);
}
finish();
}
}
Following is the service code.
public class MyService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand");
// do not receive all available system information (it is a filter!)
final IntentFilter battChangeFilter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
// register our receiver
this.registerReceiver(this.batteryChangeReceiver, battChangeFilter);
return super.onStartCommand(intent, flags, startId);
}
private final BroadcastReceiver batteryChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
checkBatteryLevel(intent);
}
};
private void checkBatteryLevel(Intent batteryChangeIntent) {
// some calculations
final int currLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_LEVEL, -1);
final int maxLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_SCALE, -1);
final int percentage = (int) Math.round((currLevel * 100.0) / maxLevel);
if(percentage==100)
{
Intent intent = new Intent(getBaseContext(), Last.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);
}
// do not forget to unregister
unregisterReceiver(batteryChangeReceiver);
} }
And when following activity start i did not receive any broadcast.
public class Last extends Activity {
Button btnCancel;
Uri notification;
Ringtone r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
btnCancel = (Button) findViewById(R.id.stopsound);
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
r.stop();
}
});
} }
As I understood,
when you start application in first time, you see nothing, just service is started and a broadcast receiver is registered. When battery level will be changed, the method checkBatteryLevel() is calling and the broadcast receiver will be unregistered. As result you have never received a new changing of battery level.

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.

Continue service when app is killed

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);
}

How to get broadcast for screen lock in android

How to get trigger that screen is locked or on in android??
i tried using SCREEN_OFF & SCREEN_ON action in broadcast receiver but it's not working.
public void onReceive(Context context, Intent intent) {
Log.d("XYZ", "Screen ON/OFF");
Toast.makeText(context, "screen",10000).show();
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
.......
}
}
in activity i have registered broadcast like-
screen is object of my broadcast receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mContext.registerReceiver(screen, filter);
Call the UpdateService.class within your MainActivity.class .
startService(new Intent(MainActivity.this, UpdateService.class));
UpdateService.class
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
public static int countOn = 0;
public static int countOff = 0;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
Log.i("UpdateService", "Started");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_ANSWER);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Log.i("viaService", "CountOn =" + countOn);
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
Log.i("viaService", "CountOff =" + countOff);
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Receiver class
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
// Log.i("via Receiver","Normal ScreenOFF" );
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
} else if(intent.getAction().equals(Intent.ACTION_ANSWER)) {
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Hey try using dynamic calling of broadcast,I tried this it will surly work...
public class MainActivity extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}

Start app when screen off

I want to open my MainActivity class when screen is off. In order to do that i make two class
ScreenReceiver.java to handle Screen OFF & Screen ON Intents:
public class ScreenReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
And UpdateService for implementing ScreenReceiver:
public class UpdateService extends Service {
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
public void onStart(Context context, Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
// your code
Intent intent11 = new Intent(context,MainActivity.class);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent11);
} else {
// your code
Intent intent11 = new Intent(context,MainActivity.class);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
So, when i install my app, there are no event when screen is off. please show me the problem.
Did you start the UpdateService in foreground somewhere in your application??
Firstly, intents ACTION_SCREEN_OFF and ACTION_SCREEN_ON can only be handled by a receiver registered via function registerReceiver(). Defining an IntentFilter in manifest.xml does not work for these intents.
Then, you need to make sure UpdateService:onCreate() be called in your application, otherwise ScreenReceiver:onReceiver() will never be called. You may want to do this when get intent BOOT_COMPLETED.
You may change the code to this, and do not forget define the service in manifest:
public class UpdateService extends Service {
BroadcastReceiver mReceiver = new BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
handleScreenAction(screenOff);
}
private void handleScreenAction(boolean screenOff) {
if (screenOff) {
// your code
Intent intent11 = new Intent(context,MainActivity.class);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent11);
} else {
// your code
Intent intent11 = new Intent(context,MainActivity.class);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mReceiver, filter);
}
#Override
public void onDestory() {
super.onDestory();
unRegisterReceiver(mReceiver);
}
public void onStart(Context context, Intent intent, int startId) {
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

Categories

Resources