I am having a bit of trouble with regards to the Android code I am trying to produce. What I am trying to do is simply print out a 1 if the user wants to unlock their phone, and when the program first starts, and a 0 when the user presses the screen lock to lock their phone. I thought this had to do with the Android lifecycle so I tried using onPause and onResume, but my program only prints out 0's, never 1's. The logTime method simply prints out the 1 or a 0, and the onCreate method in the MainActivity calls onResume() once. Here is my code:
MainActivity:
protected void onPause(){
if(ScreenReceiver.screenOn){
logTime(ScreenReceiver.screenOn);
super.onPause();
}
protected void onResume()
if(!ScreenReceiver.screenOn){
logTime(!ScreenReceiver.screenOn);
super.onResume();
}
Screen Receiver:
public class ScreenReceiver extends BroadcastReceiver{
public static boolean screenOn;
#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;
}
}
}
I'm not sure why it only prints out 0's. Might anyone know why? Thanks!
There is a delay between your Activity's onPause() and the actual Broadcast being received, so usually you can get "odd" (wrong) readings since the variable change hasn't happened. This receiver needs to be dynamically registered, and you also want it to receive even when the screen is off and turns back on. Usually, Receivers are unregistered in onPause() to avoid leaking, but here, we're going to use onDestroy() since that's the last method call we can use. For simplicity, I made the BroadcastReceiver right in the Activity and called logTime() outright.
Sample Code:
public class MainActivity extends Activity {
BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
if(arg1.getAction().equals(Intent.ACTION_SCREEN_OFF)){
logTime(false);
}
else if(arg1.getAction().equals(Intent.ACTION_SCREEN_ON)){
logTime(true);
}
}
};
registerReceiver(receiver, filter);
}
#Override
protected void onDestroy()
{
try{
unregisterReceiver (receiver);
}
catch (NullPointerException e){
e.printStackTrace();
}
catch (IllegalStateException e1){
e.printStackTrace();
}
super.onDestroy();
}
public void logTime (boolean screen)
{
Time now = new Time();
now.setToNow();
String lsNow = now.format("%m-%d-%Y %I:%M:%S");
TextView myText = (TextView) findViewById (R.id.myText);
myText.append (" " + lsNow + (screen ? "0" : "1"));
}
}
Everything seems right based on your code, it should always print 0...
When the screen is turned off, screenOn is set to false, your Activity's onPause is called, it prints 0.
When your application is running and onResume is called, screenOn would be true (whether the screen was just turned on or not), there, you log the opposite of screenOn, so would be 0 again...
Related
I have code below to get the status of screen. What I am trying to do is to make a kind of chronometre to measure the elapsed time while phone is open or in use in my Android application. when screen is ON, the phone is in use,I thought this way. if there is any other way, I want to know.
The answer here was not good , I have tried and It did not work onresume, I dont know why... Also I think it is not a good way, not professional. I need your help to calculate the elapsed time while the phone is in use. Thanks
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
///start calculating the elapsed time
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.screenMod) {
Toast.makeText(getApplicationContext(),"turn off",Toast.LENGTH_SHORT).show();
/////stop calculating
} else {
}
super.onPause();
}
#Override
protected void onResume() {
if (!ScreenReceiver.screenMod) {
Toast.makeText(getApplicationContext(),"turn on",Toast.LENGTH_LONG).show();
////continue calculating
} else {
}
super.onResume();
}
}
ScreenReceiver.class
public class ScreenReceiver extends BroadcastReceiver {
public static boolean screenMod = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenMod = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenMod = true;
}
}
}
You can do that without using any ui interraction. Just declare your broadcast receiver in manifest. When you get Intent.ACTION_SCREEN_ON create a variable which holds system time with System.currentTimeMillis(). Save another variable which holds When you get Intent.ACTION_SCREEN_OFF event. Calculate the difference between to values you will get phone use time in milliseconds. Sum it with sharedpreferences last time
I am developing a fingerprint sensor application that use good amount of RAM,problem may be related to memory, i tried a lot still unsolved.
Q:- When i press home button application paused and from the recent button it resumed successfully, but when i press power button then unlock my device,it show ANR instead of my application screen.
It means it is not being resumed when unlocking the device.
Please suggest or give solutions if you got my point.
NOTE:
Used device is dedicated to my application no other application will be installed or run.
Maybe you need broadcast receiver to listen screen on or off.
public class ScreenReceiver extends BroadcastReceiver {
// thanks Jason
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}
}
And in your Activity, it will be like this
public class ExampleActivity extends Activity {
#Override
protected void onCreate() {
// initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
// your code
}
#Override
protected void onPause() {
// 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
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
}
super.onPause();
}
#Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.wasScreenOn) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
}
super.onResume();
}
}
I have written a simple activity to test out services and broacast receivers and a service to go along with it. In order to know whether or not it's working I've set up a Toast within the main activity to be showed once the OnReceive() method is called. But for the life of me I can't get this to work.
These are the codes:
public class ServicesAndBroadcastIntentActivity extends Activity {
private Toast test;
private Intent intent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this,serviceD.class);
test = Toast.makeText(this,"Test",Toast.LENGTH_LONG);
test.setGravity(Gravity.CENTER,0,0);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
test.setText((intent.getStringExtra("EXTRA_MSG")));
test.show();
}
};
#Override
public void onResume(){
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(serviceD.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
}
public class serviceD extends Service{
private Intent intent;
static final String BROADCAST_ACTION = "com.mejg.ServicesAndBroadcastIntent";
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
public void onStart(){
intent.putExtra("EXTRA_MSG","hola");
sendBroadcast(intent);
stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
You are calling startService() before registerReceiver(). Both are asynchronous operations, but they will still likely occur in sequence. Hence, onStart() of your service will be called before registerReceiver() does its work, which means your broadcast goes out before your receiver is set up.
For this sort of experimentation, I recommend setting up a basic UI (e.g., one really big button) and doing the startService() call when the button is pressed.
Also, since the service calls stopSelf(), you do not need to call stopService() from the activity.
Also also, you might consider using LocalBroadcastManager for this -- same basic syntax with better performance and security, since it all stays within your process.
UPDATE
Also also also, onStart() has been deprecated for two-plus years, and your method signature for it is wrong, anyway. Please use onStartCommand(), with the right parameters.
Also also also also, use #Override when overriding methods, to help you catch these sorts of problems.
I essentially want to display a screen whenever the screen is unlocked regardless of the application already running.
Can someone just tell me how to display text as soon as the phone gets unlocked. I can take it from then on.
I have the following code up till now which I found on the net....
Suppose I want to display abc.xml as soon as the phone gets unlocked. How will i add it in the ScreenReceiver Class ?
Also I do not want to set any screen when the application runs.Do I need to run the code below as service ?
public class SampleActivity extends Activity {
//Declare the necessary variables
private BroadcastReceiver mReceiver;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy()
{
super.onDestroy();
Log.v("$$$$$$", "In Method: onDestroy()");
if (mReceiver != null)
{
unregisterReceiver(mReceiver);
mReceiver = null;
}
}
}
where the Screen Reciever class is as follows
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
Log.v("$$$$$$", "In Method: ACTION_SCREEN_OFF");
// onPause() will be called.
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
Log.v("$$$$$$", "In Method: ACTION_SCREEN_ON");
//onResume() will be called.
// Better check for whether the screen was already locked
//if locked, do not take any resuming action in onResume()
//Suggest you, not to take any resuming action here.
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
{
Log.v("$$$$$$", "In Method: ACTION_USER_PRESENT");
// Handle resuming events
}
}
}
For one, you don't display abc.xml, you display an activity, dialog, or other UI component. You can set up a broadcast receiver that listens for the ACTION_BOOT_COMPLETED intent. Once the device boot completes, you can start a sticky service to listen for the actions you have above. Presumably you'll want to display abc.xml in an activity, so you'll need to fire startActivity from one of the if() blocks above.
I am working on Android 3.0 and I need to know in my application when the device goes on sleep / turn off screen.
How can I register to this intent/event so I will be able to run some actions when this happens? Is there any action in BroadcastReceiver that notifies for this?
This page has a tutorial on exactly what you're looking for.
Code copied from that page (in order to turn this from a link-only answer to something directly useful):
1) Create a class in your application to receive the intent. For example, the following receiver stands alone and sets a static variable to be used in part 2:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}
}
2) Modify your activity to receive screen on/off events. Your receiver will check the static variable in your broadcast receiver to know the reason for the intent you just received:
public class ExampleActivity extends Activity {
#Override
protected void onCreate() {
// initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
// your code
}
#Override
protected void onPause() {
// 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
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
}
super.onPause();
}
#Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.wasScreenOn) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
}
super.onResume();
}
}