Multiple activity instances run? - android

I have 2 activities.
In my first, i have a button and when i click on it, it start the second activity .
But when i go back to my first and i click for second time my button, my second activity start but i have to go back two time to go back in my firts activity.
If a click one again a will have to go back 3 time ...
help me please. and thank you in advance :)
this is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this._that = this;
_progressDialog = new ProgressDialog(this);
EditText editText = (EditText) findViewById(R.id.MainActivityEditText);
editText.setText("T_F81D4FA3F8");
Button button = (Button) findViewById(R.id.MainActivityButton);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.MainActivityButton ) {
Log.w("MainActivity", "onClick");
_progressDialog.setMessage("Chargement en cours");
_progressDialog.show();
new Thread(new Runnable() {
public void run() {
EditText editText = (EditText) findViewById(R.id.MainActivityEditText);
String s = editText.getText().toString().replace(" ", "");
Log.i("EditText", s);
ID_APPLICATION = s;
//if (! Datas.getInstance().isUpdateDatas())
WebService.getInstance().datas(_that);
LocalBroadcastManager.getInstance(_that).registerReceiver(datasUpdateFail, new IntentFilter("datas-update-fail"));
LocalBroadcastManager.getInstance(_that).registerReceiver(datasUpdate, new IntentFilter("datas-update"));
}
}).start();
}
}
BroadcastReceiver datasUpdate = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
myStartActivity("ACCUEIL");
_progressDialog.dismiss();
}
};
BroadcastReceiver datasUpdateFail = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "Erreur : Veuillez verifier votre identifiant ou votre connexion", Toast.LENGTH_SHORT).show();
_progressDialog.dismiss();
}
};
public void myStartActivity(String page){
Intent intent = new Intent(this, PageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("page", page);
intent.putExtras(bundle);
this.startActivity(intent);
}

unregister the receiver
#Override
protected void onPause() {
// Unregister receiver
LocalBroadcastManager.getInstance(this).unregisterReceiver(datasUpdate);
LocalBroadcastManager.getInstance(this).unregisterReceiver(datasUpdateFail);
super.onPause();
}

Every time you get into this activity you register a received. So the second time you come back, you have 2 receivers registered. Therefore when you click on button 2 activities will be opened.
Try uninteresting the regiseter when you are done with it. eg. Before starting the new activity.
LocalBroadcastManager.getInstance(_that).unregisterReceiver(datasUpdateFail);
LocalBroadcastManager.getInstance(_that).unregisterReceiver(datasUpdate);

Related

android, how to pop a dialog from some non ui module

How to open a dialog when from some non ui module when there might be different activity in display?
Let's say there could be multiple activities stacked, Activity_A, Activity_B, Activity_C. The common service module may running on non ui thread and running into case need to popup a dialog.
It could be done by passing the handler from all active activities to the module and post message to let the activity to pop dialog.
But that need some management in terms of passing the handler and determine who is on top of the view.
Is there a better way?
You can show dailog from non-ui thread using BroadcastReceiver
Understand Flow:
public class Sample extends Activity {
BroadcastReceiver updateUIReciver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateUIReciver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//UI update here
ShowFailedDailog(null, getString(R.string.mms_sending_service_failed_txt));
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("update.from.nonui");
registerReceiver(updateUIReciver, filter);
}
void ShowFailedDailog(String title, String message) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.import_backup_popup);
TextView Save = (TextView) dialog.findViewById(R.id.tOk);
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView cancel = (TextView) dialog.findViewById(R.id.tCancel);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
NON UI:
public class NonUiSerive extends Service {
Context context;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
// ..... your tasks
if (SomeFlagUpdateTrue) {
Intent local = new Intent();
local.setAction("mms.seding.failed");
context.sendBroadcast(local);
}
}
this.stopSelf();
return 0;
}
}
Similarly register receiver all your three class it will update in every activity not restricted to one.
After try out I think the simplest is to use application context to open a activity for dialog. This way it would not care who's the current activity on top.
Intent dialogIntent = new Intent(applicationCotext, DialogActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
applicationCotext.startActivity(dialogIntent);

How to imitate finishAffinity in Android?

The question is pretty self explanatory.
I'm doing a class that registers the activity of the user in order to avoid inactivity, after 2 minutes of no activity or everytime the user minimizes the app, the app should close. My code is the one listed below:
public class InActivityTimer extends Activity {
public static final long DISCONNECT_TIMEOUT = 2*60*1000; // 2 min = 2 * 60 * 1000 ms
public static int ESTADO_ACTIVIDAD=0; //Variable para saber si la actividad está al frente o no.
private static Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
//finish();
finishAffinity();
Intent intent = new Intent(getApplicationContext(),VentanaInactividadCierreAplicacion.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
};
public void resetDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction(){
resetDisconnectTimer();
}
#Override
public void onResume() {
super.onResume();
ESTADO_ACTIVIDAD ++;
resetDisconnectTimer();
comprobarEstado();
}
private void comprobarEstado() {
if (ESTADO_ACTIVIDAD == 0){
// Intent startMain = new Intent(getApplicationContext(), SplashScreen.class);
// startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(startMain);
// finish();
finishAffinity();
Toast.makeText(getApplicationContext(), "RandomPassGEN cerrado por seguridad", Toast.LENGTH_SHORT).show();}
}
#Override
public void onStop() {
super.onStop();
ESTADO_ACTIVIDAD--;
stopDisconnectTimer();
comprobarEstado();
}
/* #Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(),"La aplicación se reiniciará por seguridad", Toast.LENGTH_SHORT).show();
finishAffinity();
}*/
}
As you can see, I'm using finishaffinty twice. How could I do it withous using that command? I'd like to avoid it because using finishAffinity() needs android +4.1
Thank you so much for your help.
To close your application, do the following:
Intent intent = new Intent(this, MyRootActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("exit", true);
startActivity(intent);
MyRootActivity should be the root activity of your task (this is the one with ACTION=MAIN and CATEGORY=LAUNCHER in the manifest).
In MyRootActivity.onCreate() add the following after super.onCreate():
if (getIntent().hasExtra("exit")) {
// User wants to exit, so do that
finish();
return;
}
... here is the rest of your onCreate() code
This will only work if MyRootActivity doesn't call finish() when it starts the next Activity in your workflow. If MyRootActivity does call finish() when it starts the next Activity, you should change it so that it doesn't. In that case you will need to handle the case where the user BACKs into MyRootActivity as a special case.

Broadcast receiver popup message in android

In my application i using a broadcastreceiver to receive a incoming call and shown a some details to user. It works fine, but when i opened the application and incoming call is received, it shows at top of application, not the top of incoming call screen. How to solve this issue ?
thanks in advance
Broadcast Receiver
public void onReceive(final Context context, final Intent intent) { // 1
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); // 2
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) { // 3
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); // 4
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(context, Test1.class);
i.putExtras(intent);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(i);
}
}, 2000);
}
}
Message Showing Activity
public class Test1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.popup);
WindowManager.LayoutParams wmlp = getWindow().getAttributes();
wmlp.gravity = Gravity.BOTTOM | Gravity.LEFT;
String number = getIntent().getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
TextView tv1 = (TextView)findViewById(R.id.tv1);
tv1.setText(number);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText(MyApp.mDbh.check(number));
new Handler().postDelayed(new Runnable(){
public void run() {
finish();
}
}, 10 *1000);
}
}

neither onActivityResult( ) nor notifyDataSetChanged() work

I've read many answers on the same question but still I do not understand why my code doesn't work properly. I have a problem with (as I think) exchanging data between two activities.
I have 2 activities - the first contains ListView and an Add button.
When user presses Add new activity starts with the form to fill. When user completes the form he/she presses OK and my first activity starts again (it really does) and it should contain new item (but it doesn't).
This is my first activity:
public class DatabaseActivity extends Activity implements OnClickListener {
ArrayList<Student> students;
StudentDatabaseAdapter adapter;
ListView lvStudentList;
ImageButton imgBtnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
students = new ArrayList<Student>();
fillArrayList();
adapter = new StudentDatabaseAdapter(this, students);
lvStudentList = (ListView)findViewById(R.id.lvStudentsList);
lvStudentList.setAdapter(adapter);
imgBtnAdd = (ImageButton)findViewById(R.id.imagBtnAddStudent);
imgBtnAdd.setOnClickListener(this);
}
public void fillArrayList() {
//code here
}
#Override
public void onClick(View v) {
Intent intent;
intent = new Intent(this, WizardActivity.class);
startActivity(intent);
}
public void addStudent(Student student) {
students.add(student);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if(resultCode==RESULT_OK)
{
if(requestCode==2)
{
if (intent == null) {return;}
Student newStudent = new Student(intent.getStringExtra("name"), intent.getStringExtra("surname"),
intent.getStringExtra("last_name"), Integer.parseInt(intent.getStringExtra("year_of_birth")), R.drawable.default_ava);
addStudent(newStudent);
adapter.notifyDataSetChanged();
}
}
}
}
And that's my second activity:
public class WizardActivity extends Activity implements OnClickListener {
EditText etName, etSurname, etLastName, etYearOfBirth;
ImageButton imgBtnOK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wizard);
etName = (EditText)findViewById(R.id.etName);
//initializing other edit texts
imgBtnOK = (ImageButton)findViewById(R.id.imgBtnOK);
imgBtnOK.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, DatabaseActivity.class);
intent.putExtra("name", etName.getText().toString());
intent.putExtra("surname", etSurname.getText().toString());
intent.putExtra("last_name", etLastName.getText().toString());
intent.putExtra("year_of_birth", etYearOfBirth.getText().toString());
setResult(RESULT_OK, intent);
startActivityForResult(intent, 2);
}
}
There is nothing wrong with your notifyDataSetChanged(). You seem to be missing the way a secondary activity communicates results back to its caller activity.
DatabaseActivity.onClick() should call startActivityForResult() instead of startActivity().
WizardActivity.onClick() should just call finish() after setResult() (remove the startActivityForResult() call, it doesn't make sense there). Also notice that the intent you provide to setResult() can be an empty intent, i.e. Intent intent = new Intent();
After the secondary activity finishes, DatabaseActivity will be back to foreground and the result will be processed by DatabaseActivity.onActivityResult().
I think you haven't to start new activity in WizardActivity
try this :
WizardActivity
......
#Override
public void onClick(View v) {
Intent intent = new Intent(this, DatabaseActivity.class);
intent.putExtra("name", etName.getText().toString());
intent.putExtra("surname", etSurname.getText().toString());
intent.putExtra("last_name", etLastName.getText().toString());
intent.putExtra("year_of_birth", etYearOfBirth.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
and in
DatabaseActivity
add if you want
#Override
protected void onResume (){
......
adapter.notifyDataSetChanged();
}

Multiple page switching in android eclipse

Consider i am using five screen pages for project "A".Each page is having switching between other pages sequentially one by one,my need is to do close all the page when i am clicking the button "exit" from the page five which is the last one.
I have used this below code,but the problem is only the last page is getting close others are not.
find my code below
Button extbtn = (Button)findViewById(R.id.but_Exit);
extbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
} });
Thanks for your time!
Make all five activities extend a BaseActivity that registers a BroadcastReceiver at onCreate (and unregisters at onDestroy).
When extbtn is clicked, send a broadcast to all those BaseActivities to close themselves
for example, in your BaseActivity add:
public static final String ACTION_KILL_COMMAND = "ACTION_KILL_COMMAND";
public static final String ACTION_KILL_DATATYPE = "content://ACTION_KILL_DATATYPE";
private KillReceiver mKillReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
...
mKillReceiver = new KillReceiver();
registerReceiver(mKillReceiver, IntentFilter.create(ACTION_KILL_COMMAND, ACTION_KILL_DATATYPE));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mKillReceiver);
}
private final class KillReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
and at extbtn's onClick call:
extbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// send a broadcast that will finish activities at the bottom of the stack
Intent killIntent = new Intent(BaseActivity.ACTION_KILL_COMMAND);
killIntent.setType(BaseActivity.ACTION_KILL_DATATYPE);
sendBroadcast(killIntent);
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});

Categories

Resources