currently I am building a very small native app for my android phone. I want to active the portable wi-fi hotspot when I click one button in the app. But I didn't know how to invoke Android API to active portable wi-fi hotspot. I know how to do it through the UI. Can anyone show me?
// code to enable portable wifi hotspot
public void EnableWifiHotspot(){
try{
WifiManager wifi_manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifi_configuration = null;
Method wifiHotspotEnabledMethod=wifi_manager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
wifiHotspotEnabledMethod.invoke(wifi_manager, wifi_configuration, true);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
//code for disabling portable wifi hotspot
public void DisableWifiHotspot(){
try{
WifiManager wifi_manager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifi_configuration = null;
Method wifiHotspotEnabledMethod=wifi_manager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
wifiHotspotEnabledMethod.invoke(wifi_manager, wifi_configuration, false);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
Related
I want to create a hidden WiFi hotspot programmatically with an android device,but I can't find an answer with [developer.android.google.cn][1]
[1]: http:///https://developer.android.google.cn/reference/android/net/wifi/WifiConfiguration. just now I saw a property named hiddenSSID, I tried to change it's value(true/false),but it did not work,could anybody help me?
private void stratWifiAp(String mSSID, String mPasswd) {
Method method1 = null;
try {
method1 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = mSSID;
netConfig.preSharedKey = mPasswd;
netConfig.hiddenSSID = true;
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(4);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
method1.invoke(mWifiManager, netConfig, true);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
Try to modify your code to be something like this:
private void stratWifiAp(String mSSID, String mPasswd) {
Method method1 = null;
try {
//通过反射机制打开热点
method1 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = mSSID;
netConfig.preSharedKey = mPasswd;
netConfig.hiddenSSID = true;
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(4);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
method1.invoke(mWifiManager, netConfig, true);
return netConfig;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
//return netConfig; or try to add here IF ONLY YOU ADDED THE ABOVE ONE!
}
I am working on A2DP connection with headset and other Bluetooth device but when I connect Bluetooth device but when I Disconnect but It didn't disconnect with it. My code is:
try {
Method connect = mA2dpService.getClass().getDeclaredMethod("disconnect", BluetoothDevice.class);
connect.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
Finally I found
Call getProfileProxy to get a2dp proxy
adapter.getProfileProxy(c, listner, BluetoothProfile.A2DP);
listenr should implement onA2DPProxyReceived.
Then Callback onA2DPProxyReceived will be called.
public void onA2DPProxyReceived (BluetoothA2dp proxy) {
Method disconnect = null;
try {
disconnect = BluetoothA2dp.class.getDeclaredMethod("disconnect", BluetoothDevice.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
BluetoothDevice device = findBondedDeviceByName(mBtAdapter, myDevice);
disconnect.setAccessible(true);
try {
int result = disconnect.invoke(proxy,device);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
Refer to sites below
getDeclaredMethod : https://www.tutorialspoint.com/java/lang/class_getdeclaredmethod.htm
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothA2dp.java
Invoking : https://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("test", "test");
configBuilder.setResource("test");
configBuilder.setServiceName("37.139.26.142");
configBuilder.setHost("37.139.26.142");
configBuilder.setPort(5222);
configBuilder.setSendPresence(true);
configBuilder.setDebuggerEnabled(true);
configBuilder.setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.required );
SASLMechanism mechanism = new SASLDigestMD5Mechanism();
SASLAuthentication.registerSASLMechanism(mechanism);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.unBlacklistSASLMechanism("DIGEST-MD5");
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
try {
connection.login();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I'm currently trying to handshake my android application and my openfire server(working on ubuntu). But I couldnt. I dont get any fail or something. Just nothing happens. And that feels bad.
Did you try to send a message? Are you sure that you are not connected?
Did you check on Openfire admin that your test user is not connected?
First I suggest you to try to send a message:
ChatManager chatmanager = ChatManager.getInstanceFor(connection);
Chat newChat = chatmanager.createChat("anotheruser#yourdomain", new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Howdy!");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
I got this code from : http://www.igniterealtime.org/builds/smack/docs/latest/documentation/messaging.html
Another suggestion is to disable the SecurityMode, just for a test.
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
If nothing of this works, try to use the configuration below, which works for me.
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serverAddress);
config.setHost(serverAddress);
config.setPort(5222);
config.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(config.build());
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
try {
connection.login(loginUser, passwordUser);
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
First I find out this is not about Android part, this is about Openfire part. Because I couldnt connect it with Spark and I saw this in Logcat;
W/System.err: org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: '37.139.26.142:5222' failed because java.net.SocketTimeoutException: failed to connect to /37.139.26.142 (port 5222) after 30000ms
Then I did some research and tried somethings and I saw it is about Ubuntu(at least for me). Then I moved my openfire server to Centos. Then I could be able to connect with Spark to it. Then I got another problem.
org.jivesoftware.smack.SmackException: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
And I solved this problem with this code below. I hope this can help others.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SmackConfiguration.DEBUG = true;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("test", "test");
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("test");
configBuilder.setServiceName("enter your server ip here");
configBuilder.setHost("eneter your server ip here");
configBuilder.setPort(5222);
configBuilder.setSendPresence(true);
configBuilder.setDebuggerEnabled(true);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
SASLAuthentication.unBlacklistSASLMechanism("PLAIN");
XMPPTCPConnection connection;
connection = new XMPPTCPConnection(configBuilder.build());
// Connect to the server
try {
connection.connect();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
// Log into the server
try {
connection.login();
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hello I'm trying to create an access point from my app. I can stand up the AP but not with the configuration that I set. I am using an htc Sensation XE
WifiManager wifiManager = (WifiManager) rc.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
Method[] wmMethods = wifiManager.getClass().getDeclaredMethods();
boolean methodFound=false;
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.SSID = "MyWifiAP";
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
for(Method method: wmMethods){
if(method.getName().equals("setWifiApEnabled")){
methodFound=true;
try {
boolean apstatus=(Boolean) method.invoke(wifiManager, netConfig,true);
for (Method isWifiApEnabledmethod: wmMethods){
if(isWifiApEnabledmethod.getName().equals("isWifiApEnabled")){
while(!(Boolean)isWifiApEnabledmethod.invoke(wifiManager)){
};
for(Method method1: wmMethods){
if(method1.getName().equals("getWifiApState")){
int apstate;
apstate=(Integer)method1.invoke(wifiManager);
for(Method method2: wmMethods){
if(method2.getName().equals("getWifiApConfiguration")){
try {
netConfig=(WifiConfiguration)method2.invoke(wifiManager);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("CLIENT", "\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n");
if (apstate==0) {
Log.d("basura", "apstate es: "+apstate);
}
}
}
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
When I print:
Log.e("CLIENT", "\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n");
I get:
nSSID:null
nPassword:null
I have the same problem with my HTC Desire and Android 2.2.2. It seems that many(or all) HTC devices can't be configured this way. HTC has probably rewrote some of the code and restrict some of the hidden features. You are using methods, which are not offically in the API (eg setWifiApEnabled) through reflection. In my case the hotspot will be created, but with the default configuration. Probably you have the same issue. It will work for some other devices thought
I currently am designing an app which needs to connect to a device, write/read data, and close the connection reliably. Currently I have the write/read solid. My disconnect and then reconnect is terribly unreliable, and often actually crash the phone.. and sometimes Eclipse. I've been looking through numerous articles trying to figure it out and.. no luck..
****CONNECT FUNCTION**
public boolean connect()
{
ConfigData.getInstance();
BluetoothSocket tmp = null;
BluetoothDevice device = ConfigData.m_SharedBluetoothDevice;
Method m;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);//(BluetoothSocket)
m.invoke(device, 1);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
ConfigData.m_SharedBluetoothSocket = tmp;
try {
ConfigData.m_SharedBluetoothSocket.connect();
ConfigData.bIsBTConnected = true;
} catch (IOException e) {
try {
closeSocket();
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e.printStackTrace();
} catch (IllegalAccessException e1) {
e.printStackTrace();
} catch (InvocationTargetException e1) {
e.printStackTrace();
}
ConfigData.m_SharedBluetoothSocket = tmp;
try {
ConfigData.m_SharedBluetoothSocket.connect();
ConfigData.bIsBTConnected = true;
} catch (IOException e1) {
ConfigData.m_BluetoothException += e1.toString();
ConfigData.bIsBTConnected = false;
return false;
}
e.printStackTrace();
return true;
}
return true;
}
****Disconnect Function**
public void destroySocket()
{
try {
if(m_InStream != null)
{
m_InStream.close();
m_InStream = null;
}
if(m_OutStream != null)
{
m_OutStream.close();
m_OutStream = null;
}
if(ConfigData.m_SharedBluetoothSocket != null)
{
ConfigData.m_SharedBluetoothSocket.close();
ConfigData.m_SharedBluetoothSocket = null;
}
if(m_InStream == null && m_OutStream == null && ConfigData.m_SharedBluetoothSocket == null)
{
ConfigData.bIsBTConnected = false;
}
} catch (IOException e1) {
m_InStream = null;
m_OutStream = null;
ConfigData.m_SharedBluetoothSocket = null;
e1.printStackTrace();
}
}
So the disconnect is successful and returns everything null. The problem is that when I reconnect it blocks at the 2nd connect attempt and will either just sit there or completely crash the phone, causing several reboots.
Does anyone have any advice here? Its been extremely frustrating. Any help would be much appreciated!!
Thanks and Gig 'Em!
TxAg
What phone are you using? What OS? See this answer:
Disconnect a bluetooth socket in Android
The close is actually not working properly on some HTC 2.1update1 phones