Assume i have activity A that act as the root activity for my app . and form this activity i go to activity B.
I want to be able to go back from B to A Without creating new instance of Activity A.
this code is in Activity B
public void onBackPressed() {
super.onBackPressed();
// Intent intent= new Intent(getBaseContext(), MainActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
Log.d("Back", "TEST");
}
but it sill call the onCreate on activity A . What i want to do is have A in the background when activity b is started and whenever it is finished switch back to activity A
this is the manifest
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:screenOrientation="unspecified"
android:launchMode="singleTask"
android:stateNotNeeded="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME"/>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/app_name"
android:name=".SubmenuActivty" >
</activity>
According to android activity life cycle, when you launch an activity A :
Life Cycle method list :
Activity A.onResume();
Activity A.onStart();
Activity A.onCreate();
Activity Status :
Activity A : Resumed
When you launch the activity B now :
Life Cycle method list :
Activity A.onStop();
Activity B.onResume();
Activity B.onStart();
Activity B.onCreate();
Activity A.onPause();
...
...
...
Activity Status :
Activity A : Stopped
Activity B : Resumed
And when you again start A now :
Life Cycle method list :
Activity B.onDestroy();
Activity B.onStop();
Activity A.onResume();
....
....
....
Activity Status :
Activity B : Destroyed
Activity A : Resumed
This is the life cycle of an activity :
You can find the details here
According to default behavior, activity A goes to onStop() state and doesn't alive and need to create a new instance on coming back to activity A. All I know - there is no way to keep alive of the A instance.
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Try it... It makes old activity to front without new instance...
You Dont need do anything. Just remove your onBackPressed() method from Activity B.
By default when you move from Activity A to Activity B, Android adds the Activity A to the backstack. When you press the back button from Activity B or finish it, it automatically restore the Activity A from backstack.
If you wish to finish your Activity B programmatically call activity's finish() method when you want to do it.
Try this
public void onBackPressed() {
super.onBackPressed();
Log.d("Back", "TEST");
}
And thats all, what you need.
Use moveTaskToBack(true);
public void onBackPressed() {
// TODO Auto-generated method stub
moveTaskToBack(true);
super.onBackPressed();
}
or You can also use finish()
Why you start an activity in onBackPressed anyway?
You should super.onBackPressed(); instead of starting new activity. Or call finish() method in you onBackPressed() method:
public void onBackPressed() {
finish();
Log.d("Back", "TEST");
}
Related
i`am new to unit testing and i have this task to write unit testing for Post API i have only the end point and api body i read a lot in google but i could not figure out how to start , any help ?
You must create a intent, fill it with data if needed, like the data extracted from the QR code and then call startActivity.
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("key", 1); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent);
finish();
I put an int in the bundle but it could be anything that implements Serializable.
You can reach direct on required screen with that pages’s activity (as shown Splash screen in below example). You can launch activity with below method.
public static void launchActivity(Activity activityName)
{
((AndroidDriver<MobileElement>) driver).startActivity(activityName);
}
How you can call this function
Suppose you have below app package and activity (its for example but you have to use for your app)
String appPackage ="my.app.helloworld";
String appActivity = "my.app.helloworld".common.activity.SplashScreen";
launchActivity(new Activity(appPackage, appActivity));
You need to set android:exported="true" in your AndroidManifest.xml file to resolve error java.lang.SecurityException
<activity
android:name="com.dsquares.lucky/.screens.mainscreens.Wallet.WalletPayment.AddFundsActivity"
android:label="wallet"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" >
</action>
</intent-filter>
</activity>
I'm having a problem with an Activity being rotated after I get back from another that has a different screen orientation.
Allow me describe the steps to reproduce this behavior:
1.I have an Activity declared in the Manifest like this:
<activity
android:name=".JobActivity"
android:label="#string/title_activity_job"
android:screenOrientation="portrait" />
As you can see, screenOrientation is set to portrait
Inside this Activity I launch another Activity with the following Intent:
Intent jobDetailsIntent = new Intent(mActivity, JobDetailActivity.class);
startActivity(cameraIntent);
This Activity screen orientation is declared to be landscape.
<activity
android:name=".JobDetailActivity"
android:screenOrientation="landscape"
android:theme="#style/ThemeFullscreen" />
The Activity JobDetailActivity when pressing a button, start another Activity waiting for a result.
startActivityForResult(getIntent(activity), requestCode);
This other Activity is declared as portrait
<activity
android:name=".QuestionsActivity"
android:screenOrientation="portrait"
android:theme="#style/ThemeFullscreen.Color" />
When I get the result from this other Activity, and after doing a couple of things, I call finish in order to return to the first Activity (JobActivity).
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// Some other stuff
this.finish();
}
}
At this point, when I get back to JobActivity I get to see the Activity in landscape (Remember it was declared as portrait) for a second and then returns to the original position.
To sum up:
A (portrait) -> B (landscape) -> C (portrait)
After receiving result from C and going back to B
A (portrait) -> B (landscape)
After calling finish from B
A (landscape)
After a second
A (portrait)
Any ideas why this may be happening? Thank you all, your help is much appreciated.
I don't understand this code:
Intent jobDetailsIntent = new Intent(mActivity, JobDetailActivity.class);
startActivity(cameraIntent);
There is a difference between the name of intent declare and intent used to start the activity.
Maybe the problem is here.
Thank you.
I would like to make an app that starts up every time the device is unlocked.
I'm new to Android and although I've read dozens of answers and the documentation there are just too many moving parts that I'm having a hard time troubleshooting.
Here is what I have ...
Structure
app
- manifests
-- AndroidManifest.xml
- java
-- DisplayMessageActivity.java
-- MainActivity.java
- res
- UnlockReceiver.java
This is in in my AndroidManifest.xml
<receiver android:name="UnlockReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
This is my UnlockReceiver.java class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.xywebsolutions.myapplication.MainActivity;
public class UnlockReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
What am I doing wrong? Is it my Structure? Do I need to add permissions before adding the receiver?
You don't need any broadcast to start/stop video.
You can use onResume() of activity lifecycle to start video. onResume will be called when activity becomes visible to user.
onPause() of activity to pause the video. You can also save current play position and start from that position when activity started again using onSaveInstanceState() function
For your case you can try this
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
two changes and this issue was fixed:
1) The "UnlockReceiver" was moved into the java folder
app
- manifests
-- AndroidManifest.xml
- java
-- DisplayMessageActivity.java
-- MainActivity.java
-- UnlockReceiver.java
- res
And
2) The receiver in the manifest needed android:exported="true" ...
<receiver android:name="UnlockReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
So I want to launch a service from a shortcut. I know that this is not possible to do directly, so I've set up a activity with the sole purpose of starting the service.
The aim of my service is to send an intent to another app and then 5 seconds later send another so I've used a CountDownTimer to do this.
However, when I launch the Activity that starts the service from the shortcut (this is getting confusing) it launches the apps UI. I don't want this, as I want it to be a background service.
What am I doing wrong. I've only just got into development, so it could be something obvious, but I've been battling with this for a few days now.
For some reason when I run it from the service it just launches the app straight away...
When I run it straight from the invisible activity it runs properly for the 1st 5 seconds fine and then loads the app...
I can't figure out why it's loading the app at all.
I've included as much info as I can that would be relevant.
Any help is appreciated!
My service:
public class Pop1_5Service extends IntentService {
public Pop1_5Service() {
super("Pop1_5Service");
}
#Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
new CountDownTimer(5000, 2500) {
public void onTick(long millisUntilFinished) {
Intent i = new Intent(INTENT_ACTION);
Bundle b = new Bundle();
b.putInt(BUNDLE_VERSION_CODE, 1);
b.putString(BUNDLE_STRING_NAME, "POP1");
b.putString(BUNDLE_STRING_VALUE, "1");
i.putExtra(BUNDLE_NAME, b);
sendBroadcast(i); }
public void onFinish() {
Intent i = new Intent(INTENT_ACTION);
Bundle b = new Bundle();
b.putInt(BUNDLE_VERSION_CODE, 1);
b.putString(BUNDLE_STRING_NAME, "POP1");
b.putString(BUNDLE_STRING_VALUE, "1");
i.putExtra(BUNDLE_NAME, b);
sendBroadcast(i); }
}
}.start();
}
}
Activity that launches service:
public class Pop1_5Activity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, Pop1_5Service.class);
startService(intent);
finish();
}
}
Subsection of Manifest:
<activity
android:name=".Pop1_5Activity"
android:theme="#android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Pop1_5Service" />
And the 'Create a Shortcut' Activity:
public class CreateShortcutActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent shortcutintent = new Intent(this, Pop1_5Activity.class);
ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutintent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Pop1_5");
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
setResult(RESULT_OK, intent);
finish();
}
}
From the look of things, it looks like CreateShortcutActivity does nothing.
Your LAUNCHER is Pop1_5Activity, so when the user presses the app icon, this Activity will run, and it launches the Service.
All the code you have showed us are "invisible", the two Activities finish() themselves, and the Service is a Service.
You might want to look at how your BroadcastReceiver handles your broadcast. For instance, does it create another Activity through PendingIntent? Is the Activity created invisible?
Maybe you should try creating a pending Service instead of pending Activity in the BroadcastReceiver.
Okey, this is weird.
I have two activities (well, more than two, but they don't matter) - AppActivity and PopupActivity. AppActivity is my main application activity and it contains my app's settings. PopupActivity is a dialog that gets opened when user clicks the button in the notification (it's a RemoteViews notification). Well, it works. Works great. But only if user closed the AppActivity by clicking the back button. If they clicked home, PopupActivity opens after a few seconds after clicking the button. Same thing happens when user closes the PopupActivity with a home button. Clicking the button in the notification doesn't open the PopupActivity instantly, but it takes a few seconds to kill the previous activity that still exists somewhere in the background.
I've tried calling finish() in the onStop and onPause methods, but it doesn't fix my problem.
Edit: Here's the code I have:
Manifest:
<activity
android:name="cc.lupine.quicksocial.AppActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize" android:noHistory="true" android:clearTaskOnLaunch="true" android:finishOnTaskLaunch="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:configChanges="orientation|screenSize"
android:excludeFromRecents="true"
android:showOnLockScreen="false"
android:theme="#android:style/Theme.Holo.Light.Dialog.NoActionBar.MinWidth"
android:name="cc.lupine.quicksocial.PopupActivity"
android:noHistory="true"
android:launchMode="singleInstance"
android:taskAffinity=""
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<service android:name="cc.lupine.quicksocial.ShareService"></service>
ShareService.java (just a function that gets called when user clicks a button in the notification):
public static void startSharing(Context ctx, int n) {
Log.d("sn", "startsharing called in shareservice");
if(n == 1 || n == 2)
{
Intent i = new Intent(ThisApplication.getAppContext(), PopupActivity.class);
i.putExtra("shareType", n);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY|
Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_SINGLE_TOP|
Intent.FLAG_ACTIVITY_CLEAR_TASK|
Intent.FLAG_FROM_BACKGROUND|
Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);
} else if(n == 3) {
// doesn't matter for now
}
}
PopupActivity.java (fragments):
public class PopupActivity extends Activity implements OnDataPass {
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("sn", "oncreate called in popupactivity");
super.onCreate(savedInstanceState);
instanceOfPopupActivity = this;
setContentView(R.layout.activity_popup);
ShareFragment sfrag = new ShareFragment();
Bundle args = new Bundle();
Bundle extras = getIntent().getExtras();
try {
//doesn't matter
} catch(Exception e) { e.printStackTrace(); finish(); }
sfrag.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contFragment, sfrag);
fragmentTransaction.commit();
}
#Override
public void onPause()
{
Log.d("sn", "onpause called in popupactivity");
finish();
super.onPause();
}
#Override
public void onStop() {
Log.d("sn", "onstop called in popupactivity");
super.onStop();
}
#Override
public void onDestroy()
{
Log.d("sn", "ondestroy called in popupactivity");
super.onDestroy();
}
}
And if I open the popup for the first time:
05-26 14:37:14.149: D/sn(7218): startsharing called in shareservice
05-26 14:37:14.179: D/sn(7218): oncreate called in popupactivity
But when I close the popup with a home button and try to open it again:
05-26 14:38:11.620: D/sn(7218): startsharing called in shareservice
05-26 14:38:14.103: D/sn(7218): oncreate called in popupactivity
It takes a lot of time for onCreate to be called. And now, what's the reason?
I think you are focusing on the wrong problem (killing the activity) instead of focusing on the real problem (10 seconds to start it again).
First you need to understand WHY it is taking 10 seconds to open it if you exited the other acitivty with the home key!
If you posted more details (with source code) it would have been easier to understand and help you!
call finish() when you want to close app. Call finish() on both activities and watch out popup window has to be focusable to handle click.