I created an Activity and a View for my apps. Inside the view, I have one thread that acts like a server.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MainView(this));
}
}
public class ServerView extends View {
public ServerView(Context context) {
super(context);
server.startServer();
}
}
when I pressed backButton, My apps wasnt destroyed.I destroyed it manually, but my thread is still running in the background. I need to catch backButton event so I used this
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
server.shutDown();
}
return super.onKeyDown(keyCode, event);
}
this function cant stop my Thread. I dont know how to destroy my mainActivity from the view? any suggestion?
put this code in main activity and access it from your server view
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
server.shutDown();
}
return super.onKeyDown(keyCode, event);
}
access activity object in your server view and call this code
You'd better override Activity.finish()
method and clear any occupied resources (like server.shutDown()
in your case) there.
simply call finish()
it will work as you want
you can use finish() method to destroy your activity. And to destroy your thread running in background use return statement or,
if(thread != null)
{
Thread t1 = thread;
thread = null;
t1.interrupt();
}
In my opinion,if you want to destroy Activity,you can use Activity.finish()
.
if you want destroy any Thread,you canSystem.exit(0);