Reputation: 59148
I'm surprised I cannot find any info on the internet on this common situation: How can I start an internet connection? I looked at ConnectivityManager
but it seems it is just for monitoring network connectivity.
PS: The phone will be rooted, so it is not a problem.
Upvotes: 6
Views: 2419
Reputation: 15619
You can indeed turn wifi on or off (see also this article) but there is no guarantee that if wifi is turned on there will be an internet connection.
The ConnectivityManager only allows you to inspect the current connectivity state. You cannot use it to enable a connection. Also the ConnectivityManager has no knowledge if an active network connection is an internet connection, but it is easy to check this yourself (see this post for example).
Upvotes: 1
Reputation: 59148
I found the following solution:
1) Add preferred wifi/APN(Access Point Name) configuration to phone settings
2) Enable Wifi/APN
3) Connection will be established automatically
Wifi configuration is straightforward and the following page shows how it could be done:
How to programmatically create and read WEP/EAP WiFi configurations in Android?
APN configuration is tricky. Android has some hidden API's that allow you to access/modify these settings, and you need to use Reflection
to do this. This might of course break with future versions of Android. The following page explains how to access/modify those settings:
http://blogs.msdn.com/b/zhengpei/archive/2009/10/13/managing-apn-data-in-google-android.aspx
Upvotes: 1
Reputation: 20936
If you want simply enable WiFi you can use this method:
private boolean changeWifiState(boolean state) {
final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(state);
return wifi.isWifiEnabled();
}
Check the permissions required for this. I think you should add these permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
Upvotes: 2
Reputation: 9115
Sockets are what you need. To get your basic info on them, read it here: http://en.wikipedia.org/wiki/Internet_socket You don't have to read it all, but I think its important you read atleast all of the "implementation issues" to get familiar with the socket methods. Those methods are, of course, implemented differently for each platform (Windows, Android...) but they usually do the same everywhere. So once you understand what each one does, you can work with sockets in any platform with ease.
This diagram (From wiki) helps to demonstrate the sockets usage:
You are in the client side. So just create a socket and call the connect
method for the IP address of your server.
Personally, I have never used sockets in Android development. But I think you should use this class: http://developer.android.com/reference/java/net/Socket.html
Upvotes: 0