Interrupt starting of an activity
This is probably a trivial question for experienced devs, but since I'm comming from PHP I'm struggling with the following problem:
I'm starting an activity. First thing it does ( in onCreate() ) is checking if a network connection is available. If not, I'm showing a dialog. So far it's working. However, in that case, I'd like to stop the startup-routine (onCreate, onResume, ...). How can I do that?
I've now changed my approach to putting e开发者_开发知识库verything in try/catch constructs, but many functions throw the same IOException error - how can I distinguish and show the appropriate message/dialog ? (eg: no wifi/3g available, no http connection possible, downloaded file is empty etc) ?
I've looked for tutorials but haven't found any that go more in detail but the obvious "try/catch" explanation...
Move code from onCreate() to separate method ex. init()
. Test network connection in onCreate(), when passed invoke init()
, if not - finish()
.
@Override
protected void onCreate(Bundle savedInstanceState) {
if(isConnectionAvailable()){
init();
}else{
Toast.makeText(this, "Not connected", Toast.LENGTH_SHORT).show();
finish();
}
}
public boolean isConnectionAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
return (activeNetworkInfo != null) && activeNetworkInfo.isConnected();
}
It would be better to check this before you start your Activity
or you can call finish()
on your Activity
if you don't have internet connection.
After checking connection , if you have not net connection ,then finish()
your activity so it will stop further process automatically
For Checking all connection See my answer there
精彩评论