Ask if the screen is on/off in onStop() onPause() - android

i want to know in my onPause() and onStop() method if it was called because the screen went off. Therefore i wrote a broadcastReceiver:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean screenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOn = true;
}
}
}
public class ExampleActivity extends Activity {
#Override
protected void onCreate() {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
protected void onPause() {
if (ScreenReceiver.screenOn) {
System.out.println("SCREEN TURNED OFF");
} else {
}
super.onPause();
}
#Override
protected void onResume() {
if (!ScreenReceiver.screenOn) {
System.out.println("SCREEN TURNED ON");
} else {
}
super.onResume();
}
}
how is it possible if onPause() was called, because of switching the screen off ?
maybe with this ?
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
return true;
}
return super.onKeyDown(keyCode, event);
}

ok i got it i use now
pm =(PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn() == false) { ... }

Related

How to implement onkeydown method to broadcast receiver?

I want to track volume key down when screen was off. How can I put my code in on receive method?
I want to turn on flashlight when user pressed volume down key and when screen goes off.
MyReceiver.java :
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);
}
}
You don't need to set event listener inside onReceive(). Try like this
setOnKeyListener(new View.OnKeyListener() {
#Override public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (screenOff) {
// turn on torch
return true;
}
}
return false;
}

Android BroadcastReceiver finish and open activity

I found in the forum, the code that allows me to close all activities and opening another, when the device screen turns off. I stored in a sharedpreference a boolean value which when true, must launch BroadcastReceiver. The problem is that the BroadcastReceiver is launched even when the Boolean value is false.
public class Impostazioni extends AppCompatActivity {
private BroadcastReceiver mReceiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.impostazioni);
Switch swChiusura = (Switch) findViewById(R.id.switch1);
SharedPreferences settings_chiusura = getSharedPreferences(CHIUSURA_AUTOMATICA, Context.MODE_PRIVATE);
boolean vero_falso = settings_chiusura.getBoolean("pref_chiusura_automatica", false);
if(vero_falso){
swChiusura.setChecked(true);
}else{
swChiusura.setChecked(false);
}
swChiusura.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
SharedPreferences settings_percorso = getSharedPreferences(CHIUSURA_AUTOMATICA, Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings_percorso.edit();
prefEditor.putBoolean("pref_chiusura_automatica", true);
prefEditor.apply();
}else{
SharedPreferences settings_percorso = getSharedPreferences(CHIUSURA_AUTOMATICA, Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings_percorso.edit();
prefEditor.putBoolean("pref_chiusura_automatica", false);
prefEditor.apply();
//disable reciver
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
}
}
});
#Override
protected void onPause() {
super.onPause();
SharedPreferences settings_chiusura = getSharedPreferences(CHIUSURA_AUTOMATICA, Context.MODE_PRIVATE);
boolean vero_falso = settings_chiusura.getBoolean("pref_chiusura_automatica", false);
if (vero_falso) {
/**
* initialize receiver
*/
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
// when the screen is about to turn off
if (ScreenReceiver.wasScreenOn) {
// this is the case when onPause() is called by the system due to a screen state change
Log.e("MYAPP", "SCREEN TURNED OFF");
}
} else {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
}
Receiver
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
intent = new Intent(context, Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
}
}
}
This may be a bad solution but, try putting your SharedPreferences boolean into the ScreenReceiver's if block. Because right know, when your screen goes off it works without requiring the boolean value. I mean:
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
if(sharedPref.getBoolean(yourBoolean)){ //...

Service that detects screen lock: "Unable to start service Intent"

I'm trying to catch when my device screen is turned off or on. I looked at this answer here. However I haven't quite figured it out. When I test it, I get a warning saying that the service wasn't able to be created: Unable to start service Intent... not found. I'm new to services so I was hoping someone could look over the code and see what I'm doing wrong. Here is my Receiver and Service:
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;
Home.locked = true;
Log.i("screenstate", "off");
} else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("screenstate", "on");
}else if(intent.getAction().equals(Intent.ACTION_ANSWER)) {
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}}
Service:
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
Boolean isRunning;
Context context;
Thread backgroundThread;
#Override
public void onCreate() {
super.onCreate();
context = this;
isRunning = false;
// register receiver that handles screen on and screen off logic
Log.i("UpdateService", "Started");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_ANSWER);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
isRunning = false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}}
Here is my main activity:
public class Home extends Activity {
static boolean locked = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(Home.this, UpdateService.class));
if(locked)
setContentView(R.layout.activity_home2);
else
showApps(null);
}
public void showApps(View v){
locked = false;
Intent i = new Intent(this, AppsList.class);
startActivity(i);
}}
Thanks in advance.
It looks like the service hasn't been declared in the manifest file. Add its declaration within the <application> tag:
<service android:name=".UpdateService"/>

Stop service in an activity

I'm using following code to stop my service
Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);
And this is my service that works indefinitely
public class UsageRecorderService extends IntentService {
public UsageRecorderService() {
super("UsageRecorder");
}
#Override
protected void onHandleIntent(Intent intent) {
while (true) {
UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
}
Why does not stop my service?
This code would work
public class UsageRecorderService extends IntentService {
private boolean mStop = false;
public UsageRecorderService() {
super("UsageRecorder");
}
public final Object sLock = new Object();
public void onDestroy() {
synchronized (sLock) {
mStop = true;
}
}
#Override
protected void onHandleIntent(Intent intent) {
while (true) {
synchronized (sLock) {
if (mStop) break;
}
UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
}
You can use stopService
Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);
Also I recommend to read Services guide to understand what is going there.
Activity:
sendBroadcast(new Intent(ACTION_STOP));
IntentService
public class UsageRecorderService extends IntentService {
private static final String TAG = "UsageRecorderService";
String ACTION_STOP = "com.xxx.UsageRecorderService.ACTION_STOP";
boolean stop;
public UsageRecorderService() {
super("UsageRecorder");
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
if (ACTION_STOP.equals(intent.getAction())) {
stop = true;
}
}
};
#Override public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(ACTION_STOP);
registerReceiver(receiver, intentFilter);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG,"onHandleIntent");
while (true && !stop) {
Log.i(TAG,"----running----");
//UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
#Override public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
An IntentService is designed to stop itself only when all the requests present in the work queue have been handled.Android stops the service after all start requests have been handled.

Creating my own action for BroadcastReceiver

I have an method like this:
public static boolean checkConnection(){
if(getConnection()!=null){
return true;
}else
return false;
}
I trying to listen to the result of this method throughout my application. Till my application is alive. Only inside my application
How should I create my own action so that in BroadcastReceiver I can listen to this method and show an dialog when it returns false and hide the dialog automatically when it start returning true?
How and what will be the best approach to do this?
public class BroadCastActivity extends Activity implements OnClickListener{
ConnectionReceverLocal mReceverLocal;
Button mSwithcOn,mSwitchOff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broad_cast);
/*Intent intent = new Intent();
intent.setAction("com.broadcast.myconnectionbroadcast");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);*/
mReceverLocal = new ConnectionReceverLocal();
mSwitchOff = (Button)findViewById(R.id.switchoff);
mSwithcOn = (Button)findViewById(R.id.switchon);
mSwitchOff.setOnClickListener(this);
mSwithcOn.setOnClickListener(this);
}
private void sendMessage() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.d("Connection result Checking Asynctasks", ""+ConnectionProvider.checkConnection());
return ConnectionProvider.checkConnection();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Intent intent = new Intent("com.broadcast.myconnectionbroadcast");
// Add data
intent.putExtra("message", result);
LocalBroadcastManager.getInstance(BroadCastActivity.this).sendBroadcast(intent);
}
}.execute();
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceverLocal);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mReceverLocal,
new IntentFilter("com.alignminds.broadcast.myconnectionbroadcast"));
sendMessage();
}
public class ConnectionReceverLocal extends BroadcastReceiver {
public ConnectionReceverLocal() {
}
#Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder mDBuilder = new AlertDialog.Builder(BroadCastActivity.this);
Boolean intentAction = intent.getBooleanExtra("message", false);
if(intentAction==false)
{
Log.d("Connection is false in broadcast recever", "Connection is false");
if(mDBuilder!=null)
{
mDBuilder.setMessage("No Network");
mDBuilder.create().show();
}
}else {
Log.d("Connection is true in broadcast recever", "Connection is true");
if(mDBuilder!=null)
{
mDBuilder.setMessage("Network Ok");
mDBuilder.create().show();
}
}
}
}
#Override
public void onClick(View v) {
if(v==mSwithcOn)
{
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
if(v==mSwitchOff)
{
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
}
}
Send a broadcast with whatever action you want like this
Intent intent = new Intent();
intent.setAction("my_fancy_action");
intent.putExtra(EVENT_MESSAGE, message);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Subclass BroadcastReceiver class to listen for broadcasts
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
// Do something
}
Register your receiver to listen to the broadcast
IntentFilter filter = new IntentFilter();
filter.addAction("my_fancy_action");
LocalBroadcastManager.getInstance(context).registerReceiver(myReceiver, filter);

Categories

Resources