I want to open an activity from the first one, and i want to close the first one with an intent. I tried this, but the receiver doesn't work. And i have different receivers in my application, so i want that this intent is received only from FirstReceiver. How can i do it?
public class First extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Intent close = new Intent(getApplicationContext(), Close.class);
startActivity(close);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
class FirstReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.e("FirstReceiver","FirstReceiver");
First.this.finish();
}
}
}
And this is the second class.
public class Close extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_close);
Intent myIntent = new Intent();
sendBroadcast(myIntent);
Log.e("onCreate","onCreate");
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.close, menu);
return true;
}
}
For it is better to Use startActivityForResult,onActivityRsult()
and override
onActivityResult
in yourActivity
and implement like this..call the
setResult()
in Close activity when ever you want to close the your mainActivity..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 "Close".
The above code clears all the activities except for Close. Close is the first activity that is brought up when the user runs the program. Then put this code inside the Close's onCreate, to signal when it should self destruct when the 'Exit' message is passed.
this may help you...