I'm looking for a solution to press the (non-personalized ads) button of the ActivityPolicies and close the MainActivity and then reopen the MainActivity with the correct ad.
MainActivity(principal)
public void politicas(View view) // button
{
Intent i = new Intent (this, ActivityPolicies.class);
i.putExtra("valor","politicas");
startActivity(i);
}
ActivityPolicies
public void NonPersonalizedAdvertising(View view) //button
{
SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(MensajePoliticas.this);
SharedPreferences.Editor myEditor =myPreferences.edit();
myEditor.putString("POLITICAS","LEIDO_NOACEPTADO");
myEditor.commit();
//Missing some option to close the main activity
*
*
*
//Reopen the main activity
Intent entrar=new Intent(this,MainActivity.class);
startActivity(entrar);
finish(); // Close the current activity (ActivityPolicies)
}
The goal is to close the MainActivity to reload the correct personalized or non-personalized ad. I already have the code but I am missing this option to reload the MainActivity.
Another question:
Close the main activity to reload the ads, can I have problems with some Admob rule?
Thank you very much
If your MainActivity is in backstack, you can call same activity like this:
Intent entrar = new Intent(this,MainActivity.class);
entrar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // this will open the same MainActivity instance and also give you a new intent.
startActivity(entrar);
Now in your MainActivity you can override onNewIntent
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// here you will get the new Intent. You can reload only the ads programmatically or just call `this.recreate();`
}
Related
I have MainActivity with BottomNav which includes 3 Fragments A, B, and C.
From Fragment A, I can go to Activity A and from, Activity A I can go to Activity B.
Now I want to return to specifically Fragment A from Activity B by pressing a Back button while skipping Activity A.
I've tried Intent.FLAG_ACTIVITY_CLEAR_TASK in Activity A before starting Activity B and also explicitly starting an Intent to MainActivity from Activity B but it's not giving the result I want and of course it doesn't seem like an efficient way to do it. How do I return back to the fragment?
Case 1
You need to finish Activity A after launching intent.
Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
finish();
case 2
If you want to come back on Activity A at some point then what you need is passing some flag from Activity B to A. And run this code at the beginning of your activity A.
if(extras.getBoolean("NameOfFlag", false))
{
ActivityA.finish();
}
send flag by using this code.
Intent i = new Intent(ActivityB.this, ActivityA.class);
i.putExtra("NameOfFlag", true);
startActivity(i);
finish();
Remember to finish() Activity when you don't need to come back. In this case ActivityB .
Maybe it is not the ideal solution but should work
In Activity B
#Override
public void onBackPressed() {
Intent i = new Intent(ActivityB.this, MainActivity.class);
i.putExtra("cameFromActivityB", true);
startActivity(i);
}
In Main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
Bundle extras = getIntent.getExtras();
if(extras.getBoolean("cameFromActivityB", false))
{
loadFragmentA();
}
}
// Inside the onCreate on every Activity://
getSupportActionBar().setTitle("name of the Activity here");
getSupportActionBar().setDisplayHomeAsUpEnable(true);
//then go to the manifest file in //
//before that closing bracket
set the order of your Activities; example
(you have three activities,the Main Activity,Activity2,Activity3)//
<activity android:name=".Activity2"
android:parentActivityName=".MainActivity"></activity>
What you can do is when you start your ActivityB from ActivityA just finish your activityA by finish() method.
Intent intent = new Intent(ActivityB.this,ActivityA.class);
startActivity(intent);
finish();
By doing this you will not be redirected to ActivityA instead, you will be directy redirected to your main activity when you press back button from your activityB.
I have a subActivity that can be open from my mainActivity.
For some reasons, when the user clicks on the back button go back to my mainActivity, I want my subActivity to remain open in background in order to be able to come back for later.
Questions:
how to avoid to close the subActivity when the user clicks back ?
how to come back to the mainActivity without restarting it ?
how to come back later to my opened activity without re-creating it completely ? (just want to bring it to front)
Thanks !
On you subActivity onBackPressed() add this
#Override
public void onBackPressed() {
Intent i = new Intent(SubActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
on mainActivity :
private void openSubActivity() {
Intent intent = new Intent(MainActivity.this,SubActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
override onBackPressed() and remove super from it then try opening the activity which you want to open from there for ex-
#Override
public void onBackPressed() {
// your code
}
and with the help of different activity launch modes you can achieve it
my problem is this:
I make a toast "welcome" in the Activity Main for the first time that you open the home, and it's ok,but when another page to return to the home via the back button, how can I make the toast "welcome" does not appear anymore?
the code of main activity is:
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
MyActivity actvi1;
int cont=0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnabout=(Button)findViewById(R.id.about);
//click
btnabout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// definisco l'intenzione di aprire l'Activity "aboutme.java"
Intent aboutmejava= new Intent(MyActivity.this,aboutme.class);
startActivity(aboutmejava);
}
}
);
//toast
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
code of aboutme.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutme);
Button btnback=(Button)findViewById(R.id.scritta);
btnback.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent main = new Intent(aboutme.this,MyActivity.class);
startActivity(main);
If you want it to only show the very first time the application runs, put a boolean flag in SharedPreferences and check here. There are tons of examples but here is one
If you want it to show *every time the Activity is first run when the app starts, simply replace your onClick() code with onBackPressed(). This way it won't start a new instance of your MyActivity and since the Toast code is in onCreate() and not onResume(), it won't run when you go back by clicking the back button.
SharedPreferences
This works.
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
int show = sp.getInt("firstlaunch", 0);
if(show == 0) {
Toast.makeText(getApplicationContext(), "WELCOME", Toast.LENGTH_LONG).show();
sp.edit().putInt("firstlaunch", 1).apply();
}
Place it in your home activities onCreate method.'
A shared preference is a "setting" of sort. It's a xml file that is loaded which contains all of your settings. When we first run "sp.getInt" you can see that i have a 0 after the "key - fistlaunch". The 0 is specifying what to give our Int SHOW if it can't find any shared preference with that key. Next if the int show is equal to 0 we run our Toast and then change the shared preference value to 1 so next time you run it doesn't show...
boolean b = false;
if(!b) {
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
b = true
}
kind of like that?
Are you another instance of MainActivity?
In order to return to your Main activity you should send an Intent with the flag FLAG_ACTIVITY_CLEAR_TOP (or set android:launchMode="singleTop" in launchMode in AndroidManifest.xml)
Intent main = new Intent(aboutme.this,MyActivity.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
By doing so, your main activity will be restored, instead of creating a new instance of MainActivity
In an activity, I have created a AsyncTask after hiding the activity:
this.moveTaskToBack(true);
(new MyTask(this)).execute();
To show a dialog in the task (in onPostExcecute), I want to bring the activity to front:
alertDialog.show();
Intent intent = new Intent(mainActivity, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainActivity.getBaseContext().startActivity(intent);
But a new instance of the main activity is created and shown on top of the dialog, although the application was still running (the activity has also a dialog style Theme.Dialog). How should I fix this?
Edit: According to javadoc, this code always recreates the activity and doesn't bring its previous instance to front, since startActivity is called from outside of an Activity Context.
How about adding a new piece of information to that intent, and catching it in onCreate()?
What I mean is something like this:
public class MainActivity extends Activity {
public static final String WANT_DIALOG_EXTRA = "WANT_DIALOG_EXTRA";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().hasExtra(WANT_DIALOG_EXTRA)) {
// create and show dialog
}
}
}
Then when you create your intent, add one more line like this:
intent.putExtra(MainActivity.WANT_DIALOG_EXTRA, true);
I have three activities: First, Second and Third. I used this method in Second activity:
public void onBackPressed() {
super.onBackPressed();
finish();
}
and this on Third activity:
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(Third.this, Second.class);
startActivity(i);
finish();
}
The problem is when I press back button after coming from the Third activity, I am going into First activity instead of finish(). I am successfully exiting the application when I click back button right after coming from first activity but not after coming from Third activity.
How to solve this problem?
EDIT: Thanks for the answers guys,the answer of "Ved Prakash" solved the problem for me.But i have a weird problem now.When i press back button the app is successfully exiting but the app which i minimized to Recent Apps button is coming on to the screen and exiting.For example,if i have opened Setting app before opening my app,when i press back button,my app is exiting and immediately Settings app is also opening and exiting itself.What might be the problem?
Your problem is that you don't seem to understand how Activities work. The finish() function ends the current Activity, and then you receive the previous Activity from the backstack.
My recommendation is that you should use a single Activity, and hold Fragments inside it. If you want it so that pressing the Back button ends the application at any screen that is displayed, you could do the following:
Activity XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/initial_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity that holds the Fragments:
public class InitialActivity extends FragmentActivity implements ReplaceWith
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial);
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.initial_container, new FirstFragment()).commit();
}
}
#Override
public void replaceWith(Fragment fragment)
{
getSupportFragmentManager().beginTransaction().replace(R.id.initial_container, fragment).commit();
}
}
Example for a Fragment:
public class FirstFragment extends Fragment implements View.OnClickListener
{
private ReplaceWith activity_replaceWith;
private ImageView exampleImage;
public FirstFragment()
{
super();
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_replaceWith = (ReplaceWith) activity;
}
catch (ClassCastException e)
{
Log.e(getClass().getSimpleName(), "Activity of " + getClass().getSimpleName() + "must implement ReplaceWith interface!", e);
throw e;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
exampleImage = (ImageView) rootView.findViewById(R.id.fragment_first_example_image);
exampleImage.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v)
{
if(v == exampleImage)
{
activity_replaceWith.replaceWith(new SecondFragment());
//please note that this should be done only if you are planning
//only on single-screen applications
//with no other layouts based on orientation or size
//otherwise, the Activity needs to be responsible for this, not the Fragment
}
}
}
This way, when you press the Back button, your application would end from any displayed screen.
Ok your code is wrong.
If you will look at activity source, you see that activity.onBackPressed() is calling finish(). So if call super.onBackPressed() you don't need to call finish.
Finish() is not stopping your application, it's stopping current activity.
Your code on third activity very strange. You are trying to stop activity and start another same activity.
What exactly you want to achieve?
If you want to exit application from your third activity, you need to clear your backstack. But I think you have problem with structure of your app.
Ok. then you should finish your first activity when you go to second activity like this(If you are using intent for that):
Intent it=new Intent(FirstActivity.this,SecondActivity.class);
finish();
startactivity(it);
and same for Second Activity:
Intent it=new Intent(SecondActivity.this,ThirdActivity.class);
finish();
startactivity(it);
this done your work...when you are in third activity the above activities are finished..
and when you press backButton you will be exit from application..
Good luck.
You can use -
public static final int FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the
current task, then instead of launching a new instance of that
activity, all of the other activities on top of it will be closed and
this Intent will be delivered to the (now on top) old activity as a
new Intent.
And here is how -
When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "MainActivity".
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
This explanation part is also introduced at exit-an-android-app.