I have two simple activities MainActivity
and ThreadActivity
. I call ThreadActivity
from MainActivity
.
The code ofMainActivity
:
public class MainActivity extends Activity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThreadActivity.class);
startActivity(intent);
}
});
}
}
And the code of ThreadActivity
:
public class ThreadActivity extends Activity{
private Thread myThread=null;
Button btn;
int i = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runThread();
}
});
}
void runThread(){
myThread = new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
btn.setText("#" + i);
Log.d("Thread", "I am running " + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
};
myThread.start();
}
}
When I start ThreadActivity
I run a simple thread and change button text.
My Problem
- When I loose focus from application, i.e when application becomes partially visible, and I come back I am redirected to
ThreadActivity
and the thread is still running. - When I leave application running and open a new application, and then come back, I am again redirected to
ThreadActivity
.
The problem is when I press back button, I am being redirected to first activity MainActivity
. But instead when back button is being pressed I want my application to exit. In a few words MainActivity
should not exist in the stack.
I tried setting android:noHistory="true"
for MainActivity
but I could not keep the behavior explained in bullet points working. I mean when I pause the application and restore it back, it redirected me to MainActivity
instead of ThreadActivity
.