how to restart activity when device's screen unlocked in android? - android

I have 4 activity:
FirstActivity - it shows in the first time of app running
MainActivity
SeconActivity
ThirdActivity
I want to show FirstActivity when Power Button clicked and user unlocked his/her phone. but how can i handle it that after showing FirstActivity BackgroundActivity shows again.
how can i do it?
for example in MainActivity:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
Intent checkingIntent=new Intent(getApplicationContext(),FirstActivity.class);
checkingIntent.putExtra("checking",true);
startActivity(checkingIntent);
return true;
}
return super.onKeyDown(keyCode, event);
}
and in FirstActivity
public boolean checking() {
checking_FOR_bankInfo= getIntent().getExtras().getBoolean("checking");
if (checking_FOR_bankInfo){
...
}
return cdo_state;
}

Try below code in every activity's onPause() method:
#Override
protected void onPause() {
super.onPause();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean screenOn;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
screenOn = pm.isInteractive();
} else {
screenOn = pm.isScreenOn();
}
if (!screenOn) { //Screen off by lock or power
Intent checkingIntent = new Intent(this, FirstActivity.class);
checkingIntent.putExtra("checking",true);
checkingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(checkingIntent);
finish();
}
}

#Override
protected void onStop()
{
super.onStop();
Log.d(tag, "MYonStop is called");
// insert here your instructions
// you can call new activity here.
}
when you press the button HOME the onStop() method is called.

Related

Android Detect Pressing On Power Key

My Application needs to know if the screen went off due to timeout or the user clicked the power button.
I decided to check if the power button was pressed.
I read some Q&A here and came up with this :
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
Log.w("Test", "Power button down detected");
return true;
}
return false;
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
Log.w("Test", "Power button up detected");
}
return false;
}
}
I also added this:
<uses-permission android:name="android.permission.PREVENT_POWER_KEY"/>
This doesn't work, it doesn't print the log.
Try to yseing from BroadcastReceiver:
public class MyBroadCastReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//DO HERE
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//DO HERE
}
}
}
and your manifest:
<receiver android:name=".MyBroadCastReciever">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
The onKeyDown method, no longer detects the single Power Key click. It does however detect the long press. Here's a very simple trick to capture it, and to differentiate from other buttons and other user's activities that would bring the app to the background.
PwrKeyShortPress = true; // set the default value in your class
....
....
#Override
public void onUserLeaveHint(){
PwrKeyShortPress = false;
super.onUserLeaveHint();
}
#Override
public void onStop() {
if (PwrKeyShortPress) {
// Do something for single Power Key click.
}
PwrKeyShortPress = true;
super.onStop();
}
go this way
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
// Power Button pressed
return true;
}
return super.onKeyDown(keyCode, event);
}
EDIT
you can listen to the screen ON/OFF this way
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//do something
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//do something else
}

Raising a toast when Power Button is pressed twice

What i am trying to do is ,double clicking the power button will raise a toast "Sending Message", doesn't matter if screen is On or Off.What i have done is , i have recorded the time duration of the clicks on power button & If the difference b/w the current click and previous click duration is less than a 1sec, then it will raise the toast. But its raising the toast on the single click also. Please Help me out
1.MainActivity.java
public class MainActivity extends Activity {
#Override
public 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);
BroadcastReceiver mReceiver = new CloseSystemDialogsIntentReceiver();
registerReceiver(mReceiver, filter);
}
#Override
protected void onPause() {
// when the screen is about to turn off
if (CloseSystemDialogsIntentReceiver.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 (!CloseSystemDialogsIntentReceiver.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();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
// Do something here...
Log.d("ONKEYDOWN", "ONKEYDOWN");
event.startTracking(); // Needed to track long presses
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_POWER) {
// Do something here...
Log.d("onKeyLongPress", "ONKEYDOWN");
return true;
}
return super.onKeyLongPress(keyCode, event);
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
Log.d("dispatchKeyEvent", "ONKEYDOWN");
return true;
}
return super.dispatchKeyEvent(event);
}
}
2.CloseSystemDialogsIntentReceiver.java
public class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
static long prevTime=0;
static long currTime=0;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
prevTime = System.currentTimeMillis();
Log.d("CHECK IN RECIVER WHEN ON","CHECK IN RECIVER WHEN ON");
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.d("CHECK IN RECIVER WHEN ON","CHECK IN RECIVER WHEN OFF");
currTime = System.currentTimeMillis();
wasScreenOn = true;
}
if ((currTime - prevTime) < 1000 && (currTime - prevTime)>-1000 ) {
if ((currTime - prevTime) < 1000 ) {
Toast.makeText(context, "double Clicked power button",
Toast.LENGTH_LONG).show();
Log.e("eciver ", "double Clicked power button");
currTime = 0;
prevTime = 0;
}
}
}
}
You should unregister the broadcast receiver in onDestroy and secondly this kind of system event should be handled in a Service not a foreground activity that can be destroyed when the screen goes off. Your activity can lose all state and get recreated between these presses.
Edit your code like this:
public class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
static long prevTime=0;
static long currTime=0;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
Log.d("CHECK IN RECIVER WHEN ON","CHECK IN RECIVER WHEN ON");
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.d("CHECK IN RECIVER WHEN ON","CHECK IN RECIVER WHEN OFF");
wasScreenOn = true;
}
if (prevTime == 0) {
// power button first time pressed or after you double-pressed
prevTime = System.currentTimeMillis();
} else if (((currTime = System.currentTimeMillis()) - prevTime) < 1000 ) {
// second press under 1s(double-pressed), reset prevTime
Toast.makeText(context, "double Clicked power button",
Toast.LENGTH_LONG).show();
Log.e("eciver ", "double Clicked power button");
prevTime = 0;
} else {
// second press over 1s, considered as first press for next checking
prevTime = currTime;
}
}
}

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

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) { ... }

I want to end the whole application when user click back button in android

I want to end the whole application when user click back button in android.Currently It again go to previous opened activity.
I also try override onBackPressed() but it doesnt work.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
enter code here
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
return;
}
Try this, start your application from a Activity that will act as your Root.
public class Root extends Activity {
public void onCreate() {
super.onCreate();
handleIntent();
}
public void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent();
}
private void handleIntent() {
boolean end = getIntent.getBooleanExtra("End");
if (end) {
finish();
} else {
Intent intent = new Intent(this, MyRealFirstActivity.class); // where this is the class that you want the user to see when they launch your app.
startActivity(intent);
}
}
public void onResume() {
super.onResume();
finish();
}
}
Then inside the activity that you want the back button to end the app, do the following:
public class LastActivity extends Activity {
public void onBackPressed() {
Intent intent = new Intent(this, Root.class);
intent.putExtra("End", true);
intent.addFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
This way all the activities that were started in between you launching the app and then hitting the back button, will all be finished() for you. This essentially will clean the slate of the app from start to finish and then exit.
In this case you need to finish activity, so your current activity will be closed by using finish() method. but you should also write finish() in each and every previous activities, where you call intent(start another activity). Hope it makes clear.
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.finish();
startActivity(intent);
}
Here we have two methods to finish or kill the app on back button pressed.
Using finish() which closes or finishes the current activity on android screen.
for example : you have 2 activities i.e A & B. You ll go from A activity to B activity using intent, now foreground acitivity is B, you want to go back & kill B activity & goto A acitivity use finish() onclick of backbutton. If your on A activity then it closes the app. see below code.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
}
return super.onKeyDown(keyCode, event);
}
Using android.os.Process.killProcess(android.os.Process.myPid()); which kills the app i.e force close the app & goto the home screen.see below code.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Kills & force closes the app
android.os.Process.killProcess(android.os.Process.myPid());
}
return super.onKeyDown(keyCode, event);
}
Here's the way I did it in my app: ActivityA is the first one to start; it in turn starts ActivityB. In ActivityB I may encounter an error, in which case I Want to return to activityA, or everything may finish correctly, in which case I want to "finish" the app altogether.
In ActivityA:
public class ActivityA extends Activity {
...
private final static int REQUEST_ACT_B = 1;
...
private void startChild() {
startActivityForResult(new Intent(this, ActivityB.class), REQUEST_ACT_B;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_TASK && resultCode == ActivityB.RESULT_OK) {
this.finish();
}
}
}
And then in ActivityB:
public class ActivityB extends Activity {
...
public final static int RESULT_OK = 1;
public final static int RESULT_ERROR = 2;
...
private void finishWithError() {
setResult(RESULT_ERROR);
finish();
}
private void finishSuccessfully() {
setResult(RESULT_OK);
}
}
Essentially, ActivityA starts ActivityB and expects a result back. If it receives back result "OK", then it closes itself and the user is none the wiser: the app has finished. If it received result "error", then ActivityA stays open.

Listening for HOME button press and relaunch activity

I am trying to prevent the HOME button KeyPress when a Service is running
protected void onPause () {
if (isMyServiceRunning())
{
Intent Act2Intent = new Intent(PhysicalTheftDialog.this, PhysicalTheftDialog.class);
startActivity(Act2Intent);
}
else {
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("nyp.android.project.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
But everytime when i press my HOME button the application crashes.
See, for security reasons android developers itself are not allowing us to change any kind of behaviour with home button. But even though if you really want to disable the home button press you can do this by adding below code:
#Override
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME) {
Log.i("Home Button","Clicked");
}
if(keyCode==KeyEvent.KEYCODE_BACK) {
finish();
}
return false;
}

Categories

Resources