How to connect android wifi to adhoc wifi? - android

I'm new on the android system.
Is this correct, the android 2.2.1 WIFI only detects non-ad hoc wireless network?
I was wondering if there's a way to connect my android to an ad hoc network set-up from my laptop.

You are correct that this is currently not natively supported in Android, although Google has been saying it will be coming ever since Android was officially launched.
While not natively supported, the hardware on every android device released to date do support it. It is just disabled in software, and you would need to enable it in order to use these features.
It is however, fairly easy to do this, but you need to be root, and the specifics may be slightly different between different devices. Your best source for more informationa about this, would be XDA developers: http://forum.xda-developers.com/forumdisplay.php?f=564.
Most of the existing solutions are based on replacing wpa_supplicant, and is the method I would recommend if possible on your device. For more details, see http://szym.net/2010/12/adhoc-wifi-in-android/.
Update: Its been a few years now, and whenever I need an ad hoc network connection on my phone I use CyanogenMod. It gives you both programmatic and scripted access to these functions, and the ability to create ad hoc (ibss) networks in the WiFi settings menu.

If you specifically want to use an ad hoc wireless network, then Andy's answer seems to be your only option. However, if you just want to share your laptop's internet connection via Wi-fi using any means necessary, then you have at least two more options:
Use your laptop as a router to create a wifi hotspot using Virtual Router or Connectify. A nice set of instructions can be found here.
Use the Wi-fi Direct protocol which creates a direct connection between any devices that support it, although with Android devices support is limited* and with Windows the feature seems likely to be Windows 8 only.
*Some phones with Android 2.3 have proprietary OS extensions that enable Wi-fi Direct (mostly newer Samsung phones), but Android 4 should fully support this (source).

If you have a Microsoft Virtual WiFi Miniport Adapter as one of the available network adapters, you may do the following:
Run Windows Command Processor (cmd) as Administrator
Type: netsh wlan set hostednetwork mode=allow ssid=NAME key=PASSWORD
Then: netsh wlan start hostednetwork
Open "Control Panel\Network and Internet\Network Connections"
Right-click on your active network adapter (the one that you use to connect on the internet) and then click Properties
Then open Sharing tab
Check "Allow other network users to connect..." and select your WiFi Miniport Adapter
Once finished, type: netsh wlan stop hostednetwork
That's it!
Source: How to connect android phone to an ad-hoc network without softwares.

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)
However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:
public class MainActivity extends Activity {
private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
final TextView textIp = (TextView) findViewById(R.id.Ip);
final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.BSSID = CHIPKIT_BSSID;
wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
myWifiManager.setWifiEnabled(true);
int netID = myWifiManager.addNetwork(wifiConfiguration);
myWifiManager.enableNetwork(netID, true);
textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n'
+ myWifiManager.getWifiState() + "\n\n");
btnDoSomething.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clearTextViews(textWifiManager, textIp);
}
});
btnNewScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getNewScan(myWifiManager, textWifiManager, textIp);
}
});
}
private void clearTextViews(TextView...tv) {
for(int i = 0; i<tv.length; i++){
tv[i].setText("");
}
}
public void getNewScan(WifiManager wm, TextView...textViews) {
wm.startScan();
List<ScanResult> scanResult = wm.getScanResults();
String scan = "";
for (int i = 0; i < scanResult.size(); i++) {
scan += (scanResult.get(i).toString() + "\n\n");
}
textViews[0].setText(scan);
textViews[1].setText(wm.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...
and my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Hope that helps!

You are correct, but note that you can do it the other way around - use Android Wifi tethering that sets up the phone as a base station and connect to said base station from the laptop.

Related

Is there any way to programmatically determine whether android device has builtin spellchecker?

I've read in a couple of places that spell checking cannot be turned on for EditText on Samsung devices... so it MUST be true, right? If so, there are probably other devices that also cannot spell check, such as the LG VK700 tablet my wife just bought from Verizon (don't ask).
Is there any way to detect programmatically whether a device can spell check? I'd like an option for user to turn it on or off, but not if it can't be turned on. I'd like then to have the option grayed out.
(Googling programmatically determine whether android device can spellcheck turned up this, which looks interesting, but I can't justify a lot of work (slow learner, here) for something that most users would likely turn off or ignore anyway since the flagged words would appear only in a list of words matching a user's "word pattern" (e.g., p?tt??n) for solving word puzzles.)
According to the Android Spell Checker Framework documentation, a Spell Checker Service should be exposed as a Service in the app's manifest with a specific intent filter and metadata tag:
<service
android:label="#string/app_name"
android:name=".SampleSpellCheckerService"
android:permission="android.permission.BIND_TEXT_SERVICE" >
<intent-filter >
<action android:name="android.service.textservice.SpellCheckerService" />
</intent-filter>
<meta-data
android:name="android.view.textservice.scs"
android:resource="#xml/spellchecker" />
</service>
So reasonably, we should be able to detect whether any such services are installed by trying to resolve a matching intent.
I don't have a Samsung device to test the "not found" case, but I think this should work:
TextView tv = new TextView(this);
PackageManager pm = getPackageManager();
Intent spell = new Intent(SpellCheckerService.SERVICE_INTERFACE);
ResolveInfo info = pm.resolveService(spell, 0);
if (info == null) {
tv.setText("no spell checker found");
} else {
tv.setText("found spell checker " + info.serviceInfo.name + " in package " + info.serviceInfo.packageName);
}
Regardless of whether I enable or disable spell checking in Settings, my Moto G (2013) says:.
This is the same package as the vanilla AOSP keyboard. I'd assume the problematic Samsung phones have replaced that package with their own keyboard, without replacing the spell checking service?
Note that even if you detect the existence of a matching service, the actual settings for activating it may also differ between devices...
Here's the Java code to manage Preferences to grey out the Spellchecker option or not, depending on whether user's device has it built-in.
SettingsActivity.java:
public class SettingsActivity extends Activity
{
public static boolean blnSpellcheckerPresent; // slight hack
#Override protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
// Inserted Snild's code here:
PackageManager pm = getPackageManager();
Intent spell = new Intent(SpellCheckerService.SERVICE_INTERFACE);
ResolveInfo info = pm.resolveService(spell, 0);
blnSpellcheckerPresent = (info != null);
// end insert
setContentView(R.layout.activity_settings);
}
} // end class SettingsActivity
SettingsFragment.java:
public class SettingsFragment extends PreferenceFragment
{
#Override public void onCreate(Bundle _savedInstanceState){
super. onCreate(_savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference spellchecker = getPreferenceManager().findPreference("pref_spell_check");
spellchecker.setEnabled(SettingsActivity.blnSpellcheckerPresent);
}
} // end class SettingsFragment
Here's addition to preferences.xml:
<CheckBoxPreference
android:key="pref_spell_check"
android:defaultValue="false"
android:persistent="true"
android:enabled="false"
android:title="Spell checker"
android:summary="Allow your phone's built-in spell checker to underline questionable matches"
/>
To see IF a device has builtin spellchecker, use this xml:
<spell-checker xmlns:android="http://schemas.android.com/apk/res/android"
android:label="spellchecker_name"
android:settingsActivity="com.example.SpellCheckerSettingsActivity">
</spell-checker>
(I imagine that the requirements include actually having files to DO the spell checking and since that's not MY goal, deleting the following lines from the xml at the link provided above before the closing tag above makes sense:
<subtype
android:label="#string/subtype_generic"
android:subtypeLocale="en”
/>
<subtype
android:label="#string/subtype_generic"
android:subtypeLocale="fr”
/>
To provide a spellchecker, there's a lot more work to do. Me: not interested.
)

Android 5.0 Lollipop UsbDevice missing interfaces

I wrote an android utility that talks to a few custom device over USB using the android UsbHost API. This works fine in 4.4, but in 5.0 some of the devices are missing their interfaces (getInterfaceCount() == 0).
I've been using them on a Galaxy Note 3 with CM11 and they've been working fine, but since this version of CM is unstable I tried to upgrade to CM12. The problem appeared, and I thought it might be a CM bug so I tried a simple program that enumerates devices/interfaces on a Nexus 5 with google's 5.0 release and the problem exists there too.
I created a simple test app with a Button and TextView with an OnClickListener set up as:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_usb);
Button button = (Button) findViewById(R.id.butt);
final TextView text = (TextView) findViewById(R.id.text);
final UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = "";
if( manager == null )
string += "no usb manager";
else {
for(UsbDevice device : manager.getDeviceList().values()) {
string += device.toString() + "\n";
string += String.format(" ifc: %d\n", device.getInterfaceCount());
}
}
text.setText(string);
}
});
}
The devices are hooked into a hub which is plugged into the phone with an OTG cable. When this code is run on 5.0, the devices are listed but only one device in the list actually has interfaces (and it is not always the same device). If I shell into the phone with ADB, however, I can see all the devices and their interfaces with 'cat /sys/kernel/debug/usb/devices'.
Is this a bug in android 5.0, or has the usb api changed and I am missing something? I haven't been able to find any information online.
Turns out it is a bug introduced in 5.0. There's an issue on androids bug tracker:
https://code.google.com/p/android/issues/detail?id=159529&q=usb%20interface&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars
So it's been known about since 5.0, but currently there has been no work (or even comments) from google about it.

How to find if Wi-Fi configuration is disabled in device manager policy?

I wanted to know if there is a way to find out if wifi configuration is enabled/disabled via code. I can use the following code:
UserManager um = (UserManager) context
.getSystemService(Context.USER_SERVICE);
Bundle restrictions = um.getUserRestrictions();
LogUtil.d(TAG, "restrictions bundle = " + restrictions.toString());
if (restrictions
.containsKey(UserManagerUtils.DISALLOW_CONFIG_WIFI)) {
boolean isWiFiDisabled = restrictions
.getBoolean(UserManagerUtils.DISALLOW_CONFIG_WIFI);
LogUtil.d(
TAG,
"restrictions DISALLOW_CONFIG_WIFI = "
+ isWiFiDisabled );
}
But i do not want to use this code.
Usually to find if the wi-fi configuration policy is disabled, we can go to wi-fi settings. If we can see a list of available and/or connected wi-fi networks, it means that the wi-fi configuration is enabled by our device owner. When the device owner disables wi-fi config, we cannot see list of available/connected networks.However in this case, if we are already connected to some network, then we can still have access in internet via that network.
Please let me know if there is any other way to find out the wi-fi configuration status.
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled();
but before that You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class for enabled/disabled:
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Can I turn on WiFi-Direct from code? on API-16 (Android 4.2.2)

I am developing an application with NFC and wifi direct. I get the MAC address using NFC and the Wifi Direct to transfer data. I call discoverpeers() and could get success. But there is no callback WIFI_P2P_PEERS_CHANGED_ACTION, the callback comes only when I go to settings and the select wifidirect.
This was discussed in the other question
Can I turn on WiFi-Direct from code? on Android API-14 (ICS)
"I'd like to add that WiFi direct on JB and above (at least on AOSP) is not active all the time - it only appears to be. If you look at listeners for WiFi direct, it turns itself off after some time. It turns itself back on if you open the wifi direct menu, however. You might have to have the host do a peer search or initialize itself in order to be able to be found. Likely a battery saving trick. I have also found that it's blocking, since as it accepts a connection, the entire system will lock up and fail to connect sometimes. (The system invitation) – Mgamerz "
Can anyone suggest the solution for the problem WIFI_P2P_PEERS_CHANGED_ACTION callback is not got and can get only when manually go to settings->wifi->tap on wifidirect
I used two devices Samsung galaxy nexus and nexus 7 both running on 4.2.2
There is no available API to enable wifiP2P but you can invoke method "enableP2p" from android settings 4.0.1
WifiP2pManager manager = (WifiP2pManager) getActivity().getSystemService(Context.WIFI_P2P_SERVICE);
Channel channel = manager.initialize(getActivity(), getActivity().getMainLooper(), null);
try {
Method method1 = manager.getClass().getMethod("enableP2p", Channel.class);
method1.invoke(manager, channel);
//Toast.makeText(getActivity(), "method found",
// Toast.LENGTH_SHORT).show();
} catch (Exception e) {
//Toast.makeText(getActivity(), "method did not found",
// Toast.LENGTH_SHORT).show();
}
To disable wifiP2P use this method
Method method1 = manager.getClass().getMethod("disableP2p", Channel.class);
Not from code. The user has to. That's why the demo has the link to wifi settings in the action bar.
When you call manager.discoverPeers(channel, new WifiP2pManager.ActionListener()
define onFailure and look at the reasonCode. If it's 0, then either the Wifi or WiFi direct is off.
If you look at the WiFi Direct demo app, the WifiDirectBroadcast Reciever, this piece of code looks at whether p2p is enabled specifically
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
activity.setIsWifiP2pEnabled(true);
} else {
activity.setIsWifiP2pEnabled(false);
activity.resetData();
}
Then when discover peers is called it looks at the variable set by setIsWifiP2pEnabled
thanks user3093354. to continue with your solution, in order to disable the p2p you have to invoke:
Method method1 = manager.getClass().getMethod("disableP2p", Channel.class);
//Try this it may be help you
WifiManager wifiManager = (WifiManager)this.getSystemService(this.WIFI_SERVICE);
wifiManager.setWifiEnabled(true); //True - to enable WIFI connectivity .
//False -disable WIFI connectivity.
//add this permissions in Manifest file :
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
You can load the wifi driver from a command prompt with the desired concurrency level if you are rooted:
/system/bin/insmod /system/lib/modules/wlan.ko con_mode=3
These are the values:
typedef enum
{
VOS_STA_MODE=0,
VOS_STA_SAP_MODE=1,
VOS_P2P_CLIENT_MODE,
VOS_P2P_GO_MODE,
VOS_MONITOR_MODE,
VOS_FTM_MODE = 5,
VOS_IBSS_MODE,
VOS_P2P_DEVICE_MODE,
VOS_MAX_NO_OF_MODE
} tVOS_CON_MODE;
This is for an Atheros card.

Programmatically Connect and Disconnect Android Device

I need to find a way to (using an Android application) programmatically connect and disconnect an Android device from a host.
I am using a Galaxy Nexus. My goal is to keep everything as close to stock as possible, though I have already enabled verbose debug messages in the kernel and in order to view them have enabled root access on the phone to access /proc/kmsg (and the shell command dmesg).
I am certain that there is a way to leverage root access to do what I need to do, but all of my attempts have lead to nix.
Mess with /proc/bus/usb
Mess with /dev/bus/usb
Change between MTP/PTP (unable to do programatically)
Making the Android USB gadget driver into a module <- ???
I am going to try to figure out how to do the last object on the list, as then I would be able to rmmod and insmod the resulting *.ko in my application and that would connect and disconnect the phone. I am unsure of the feasibility of this option though.
Solution came when close to a deadline, so I am almost sure it is not the best way of doing things, but it met my requirements.
Build Modded kernel (to allow hooking of particular function)
Modify kernel config to support Kprobes (set CONFIG_KPROBES to Y)
Remove "static" keyword from android_setup() definition (driver/usb/gadget/android.c)
Build that kernel
Build kernel module (which gives the actual functionality of connecting and disconnecting)
Use Kallsyms to dynamically pull the absolute address of android_setup()
Using kprobes, hook android_setup()
Set up two timers to execute every time android_setup() is called
First timer set for 2 seconds from now, Second set for 2.005 seconds from now
Both timers take a pointer to the struct usb_gadget as their data
In respective callback functions, call usb_gadget_connect() and usb_gadget_disconnect(), which forces physical disconnect followed by reconnect on the Samsung Galaxy Nexus
Build Application
Gotta have a rooted device
Simply make a shell call with SU privilege - "insmod module_name." Until you call rmmod, the module will force the device into an enumeration cycle, disconnecting and reconnecting continuously.
If you are interested in repeating these results, read the document posted here and feel free to send me any questions.
https://docs.google.com/uc?export=download&id=0B9WchRkSOWwJbi10MGhLWUljT2s
You can try to enable/disable some secured settings like Settings.Secure.USB_MASS_STORAGE_ENABLED or Settings.Secure.ADB_ENABLED (depending on what you call "connect" !)
This code should work (disabling USB mass storage):
Settings.Secure.putInt(getContentResolver(),Settings.Secure.USB_MASS_STORAGE_ENABLED, 0);
Settings.Secure.putInt(getContentResolver(),Settings.Secure.USB_MASS_STORAGE_ENABLED, 0);
InternetControl.java
public class InternetControl {
public static void EnableInternet(Context context)
{
try {
Log.i("Reached Enable", "I am here");
setMobileDataEnabled(context,true);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void DisableInternet(Context context)
{
try {
Log.i("Reached Disable", "I am here");
setMobileDataEnabled(context,false);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void setMobileDataEnabled(Context context , boolean enabled) throws Exception{
final ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class connClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = connClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conn);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
}
Manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
Enable or Disable function are static so you can call by using
classname.functionname();

Categories

Resources