using recevier in service - android

I'm trying to count time that user is using a phone, so i used receiver
it got registered in MainActivity then i am starting TimeService which is registring receiver too so it can work even if user is in other activity or app.
MainActivity
private void registerScreenReceiver(){
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
TimeService
public class TimeService 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);
}
#Override
public int onStartCommand(Intent intent, int flags, int start_id) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.e("SERVICE","ON");
} else {
Log.e("SERVICE","OFF");
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
The problem is that when i'm not using the app it's being closed by itself and receiver is no longer wroking.

You have to return START_STICKY in onStartCommand() to keep Service working.
You can also set your Service as a foreground Service but this require showing notification in the status bar which may not be a bad idea. Here is an example.
Update
It probably would be even better if you register your BroadcastReceiver in AndroidManifest.xml and start Service work from receiver when system wake it up.

Related

SCREEN_OFF Broadcast Receiver not firing inside of Service in separate process

Here is my stuff:
public class NotificationSystem extends Service implements Runnable {
private final Thread worker = new Thread(this);
private boolean alreadyRunning = false;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
ScreenManager screenManager = new ScreenManager();
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenManager, filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!alreadyRunning) {
worker.start();
this.alreadyRunning = true;
}
return START_STICKY;
}
#Override
public void run() {
while(true) {
System.out.println("Thread doing stuff");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class ScreenManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Screen is off");
}
}
}
The broadcast receiver never fires when the screen toggles off, why?
Is there some problem if there is that broadcast receiver inside of a service? Do I need anything in the manifest for SCREEN_OFF to toggle?
Is it another magical decision that the Android core team did instead of me? Maybe firing a broadcast receiver drains battery, ey?
I didn't got your question much but I got the answer for permission question of yours.
For working with Broadcast receivers you are always require to give a permission to AndroidManifest.xml which allows you to listen to state changes in your receiver. Also Register your receiver in your manifest file.
which is added by:
<uses-permission android:name="android.permission.READ_PHONE_STATE" >
I hope this helps !!
It is a firmware bug.
It's not working on my phone, but it works fine in the emulator.
Go figure.

Open app by detecting device power button press twice in android

I am trying to build an app which can be also opened by pressing device power button twice. I have followed this question's answer to build my app. But the background service is not working when the application is closed. Though it seems to work fine when the application is running. Here is the code for service LockService.java
public class LockService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder {
LockService getService() {
return LockService.this;
}
}}
BroadcastReceiver class for application ScreenReceiver.java
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(getApplicationContext(), LockService.class));
}}
Finally AndroidManifest.xml file is here.
What should i do to work the app properly?
When your application is closed, LockService gets destroyed. That is why it doesn't work. What you can do is in your Main Activity's onDestroy method, stop the service. Further, in onDestroy method of LockService, send an intent to a broadcast receiver which will start your service again. In this way, whenever your app is closed, broadcast receiver will start your service again and the code inside the service will then be executed.

Android: How to detect when phone is active and idle?

I want to create an app that will know when user is using the phone(start the screen and close the screen). After a period of time I need to call doSomething() method.
Question:
1.How can I know when user start using the phone and when he close the screen?
2.Should I use Service or IntentService? Which is better in my case?
You can try something like this using a BroadcastReceiver and a Service:
Your class using The BroadcastReceiver:
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 the service:
public static class ScreenService extends Service {
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
//Implement here your code
} else {
//Implement here your code
}
}
}

Android broadcast receiver (screen) not working on Moto g

I am trying to capture screen on/off event on moto g phone. Main activity has
Intent intentscreen = new Intent(getApplicationContext(), ScreenService.class);
startService(intentscreen);
where as "ScreenService" looks like:
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent!=null)
{
super.onCreate();
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock");
if(!wifiLock.isHeld()){
wifiLock.acquire();
}
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
registerReceiver(this.mybroadcast, filter);
return super.onStartCommand(intent, flags, startId);
}
return START_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
unregisterReceiver(mybroadcast);
if(wifiLock.isHeld()){
wifiLock.release();
}
}
while the receiver class looks like:
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Screen", "--- I Fire!");
}
}
Manifest file has the permission, but the issue is that my phone receives the event for first few hours and then it stops receiving i.e. Log.d("Screen", "--- I Fire!"); is not displayed in my log cat.
Also to add further, if I acquire PowerManager.WakeLock wakeLock it doesn't work at all, but if I acquire WifiLock wifiLock = null, this works for few hours, any suggestion that how to keep the Wifi active probably?
Any suggestion that what possibly be wrong? Or any other type of lock should I acquire? I dont want to use a lot of battery for locks.
If your service gets killed by the system due to low memory it will later be restarted with null passed as the intent. When this happens it appears you would lose broadcast receiver as you do nothing if intent is null.
Seems like it's not possible to get these broadcasts from a static receiver in the android manifest. So you'll probably have to keep your service.
Something along these lines:
public void onCreate (){
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
registerReceiver(mybroadcast, filter);
}
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
unregisterReceiver(mybroadcast);
}

How to run services even after screen off, Lock the screen?

In my application am using services move to another activity after ten minutes even the screen in off,screen locked.
my problem Service is run when screen is in ON condition,but in screen OFF or when lock the screen condition means the service is stopped after i unlock the screen means service start from there.i don't know how to do this thing.Can any one know please help me to solve this problem.
My service time coding
public class Time_out_services extends Service {
Handler mHandler;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
mHandler = new Handler();
mHandler.postDelayed(first_Task, 4 * 60 * 1000);
return Service.START_NOT_STICKY;
}
Runnable first_Task = new Runnable() {
public void run() {
mHandler = new Handler();
Intent i = new Intent();
i.setClass(Time_out_services.this, Dialog_actvity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
stopSelf();
}
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
you have to register a reciever for the screen on off
private static BroadcastReceiver mReceiver = new ScreenReceiver();
make a method "regScreenReciever()" put this code in that
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
appContext.registerReceiver(mReceiver, filter);
then create a broadcast reciever , override its onRecieve method and then put
if(intent.getAction().equalsIgnoreCase(Intent.ACTION_SCREEN_ON)){
Util.disableKeygaurd();
}
Intent linkuryIntent = new Intent(context,UpdateService.class);
context.startService(linkuryIntent);
your code will run fine

Categories

Resources