Issue
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!
Solution
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"));
}
}
Answered By - A--C
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.