I have some code that is supposed to take the SSID passed via an extra in the intent and connect to it, currently it just sets the ones I pass to it as disabled. All of the SSID's im trying to pass have already been connected to before. I' m not sure if its cause there is already an existing network configuration with the SSID, but it may have something to do with it...
package com.wt.checkin;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
public class WifiSwitcher extends BroadcastReceiver {
#SuppressWarnings("static-access")
#Override
public void onReceive(Context arg0, Intent arg1) {
Bundle extras = arg1.getExtras();
WifiManager wifiMan = (WifiManager) arg0
.getSystemService(Context.WIFI_SERVICE);
if (wifiMan.getWifiState() == 1) {
wifiMan.setWifiEnabled(true);
try {
Thread.currentThread().sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
WifiConfiguration tmpConfig = new WifiConfiguration();
tmpConfig.SSID = extras.getString("SSID");
tmpConfig.status = WifiConfiguration.Status.ENABLED;
int netId = wifiMan.addNetwork(tmpConfig);
wifiMan.enableNetwork(netId, true);
}
}
Here is the working code:
package com.wt.checkin;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
public class WifiSwitcher extends BroadcastReceiver {
#SuppressWarnings("static-access")
#Override
public void onReceive(Context arg0, Intent arg1) {
Bundle extras = arg1.getExtras();
WifiManager wifiMan = (WifiManager) arg0
.getSystemService(Context.WIFI_SERVICE);
if (wifiMan.getWifiState() == 1) {
wifiMan.setWifiEnabled(true);
try {
Thread.currentThread().sleep(2500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}**
WifiConfiguration Config = new WifiConfiguration();
WifiInfo Info = wifiMan.getConnectionInfo();
String SSID = extras.getString("SSID");
Config.SSID = "\"" + SSID+"\"";
wifiMan.addNetwork(Config);
List<WifiConfiguration> list = wifiMan.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + SSID + "\"")) {
wifiMan.disconnect();
wifiMan.enableNetwork(i.networkId, true);
wifiMan.reconnect();
break;
}
}
}
}
For others experiencing a similar problem I would like to post this related question: How do I connect to a specific Wi-Fi network in Android programmatically?
The OP looks to be doing something very similar and I notice a difference with:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wm.disconnect(); //not in OP
wm.enableNetwork(i.networkId, true);
wm.reconnect(); //not in OP
break;
}
}
I marked the lines that I think should be added. It looks like you have to format the SSID in a very specific way as well which is outlined in the other SO thread.
Related
I need to create an app to scan and gather the list of access points available, including the signal strength. For some reason every time I initiate the WifiManager.startScan() method, it returns true, but my Broadcast Receiver is never called.
Here is the code for my class:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Manages radio (wifi) information
*/
public class NetworkManager {
private final Handler handler = new Handler();
private WifiReceiver receiverWifi;
private TextView mTextView;
// true if scan is done
private boolean mDone = true;
private WifiManager mManager;
List<ScanResult> results;
// Data in form SSID, RSSI
ArrayList<HashMap<String, String>> oldData = new ArrayList<>();
ArrayList<HashMap<String, String>> data = new ArrayList<>();
public NetworkManager(Context c, TextView mTextView) {
this.mTextView = mTextView;
mManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
if (!mManager.isWifiEnabled())
mManager.setWifiEnabled(true);
receiverWifi = new WifiReceiver();
c.registerReceiver(receiverWifi,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
if (mManager.isWifiEnabled() == false)
mManager.setWifiEnabled(true);
scanAndSet();
Log.d("TAG", "Constructor after scan and set");
WifiInfo wifiInfo = mManager.getConnectionInfo();
Log.d("TAG", wifiInfo.toString());
}
/**
* Sets the SSID and RSSI from the scanned results into main data bin.
*/
// private void setNetworkData() {
// String result = "";
// oldData = data;
// data.clear();
// for(ScanResult r : results) {
// String ssid = r.SSID;
// String rssi = String.valueOf(r.level);
// HashMap<String, String> x = new HashMap<>();
// x.put(ssid, rssi);
// result += "ID: " + ssid + " - RSSI" + rssi + "/n";
// Log.d("TAG", "R: " + result);
// }
// mDone = true;
// }
public void scanAndSet() {
handler.post(new Runnable() {
#Override
public void run() {
Log.d("TAG", "Start: " + mManager.startScan());
}
});
}
public boolean isDone() {
return mDone;
}
class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "On receive broadcast receiver");
ArrayList<String> connections=new ArrayList<String>();
ArrayList<Float> Signal_Strenth= new ArrayList<Float>();
List<ScanResult> wifiList = mManager.getScanResults();
for(int i = 0; i < wifiList.size(); i++) {
connections.add(wifiList.get(i).SSID);
}
}
}
}
the scanAndSet() method is suppose to initiate the scan. The startScan() method returns true. The receiver is only called when I go to the settings and the device searches for wifi networks, I can't seem to do it programatically.
Another peculiar thing is when I want to get information for the connected access point using WifiManager.getConnectionInfo().toString(), this is what it gives.
D/TAG: SSID: <unknown ssid>, BSSID: <none>, Supplicant state: COMPLETED, RSSI: -127, Link speed: -1Mbps, Frequency: -1MHz, Net ID: -1, Metered hint: false, score: 0
I'm completely lost, is this common with all Wear devices or is the wifi api disabled?
Here is my MainActivity.java -
package com.example.printer;
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.view.Menu;
public class MainActivity extends Activity {
Button btnPrint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPrint=(Button)findViewById(R.id.button1);
btnPrint.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (isNetworkAvailable() == false) {
Toast.makeText(MainActivity.this,
"Network connection not available, Please try later",
Toast.LENGTH_SHORT).show();
} else {
File file = new File("/storage/emulated/0/Download/kpeng.pdf");
Intent printIntent = new Intent(MainActivity.this, PrintDialogActivity.class);
printIntent.setDataAndType(Uri.fromFile(file), "application/pdf");
printIntent.putExtra("title", "Android print demo");
startActivity(printIntent);
}
}
});
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
Log.e("Network Testing", "***Available***");
return true;
}
Log.e("Network Testing", "***Not Available***");
return false;
}
}
I have run this app on a Samsung s4, and the location provided ( hard coded ) is correct!
To make this app, I have followed the instructions given in http://www.androidhub4you.com/2013/10/android-printer-integration-google.html . However they have used File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/personal/xyz.pdf"); and this doesnt work for me, so I hard coded the location of the pdf file instead. Can someone please help me out? :(
Try This
String path= Environment.getExternalStorageDirectory().getPath();
File file = new File(path+"/Download/kpeng.pdf");
printIntent.setDataAndType(Uri.fromFile(file), "application/pdf");
I am working on app where i want to end outgoing call.
this is the main class
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
public class phonecalls extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
call();
}
private void call() {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123456789"));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
}
and outgoingclass is this
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.android.internal.telephony.ITelephony;
import java.lang.reflect.Method;
public class OutgoingCallReceiver extends BroadcastReceiver {
private final String TAG = "CallControl";
Context context;
String incomingNumber;
ITelephony telephonyService;
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE);
try {
// Java reflection to gain access to TelephonyManager's
// ITelephony getter
Bundle bundle = intent.getExtras();
if(null == bundle)
return;
String phonenumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.i("OutgoingCallReceiver",phonenumber);
Log.i("OutgoingCallReceiver",bundle.toString());
String info = "Detect Calls sample application\nOutgoing number: " + phonenumber;
Toast.makeText(context, info, Toast.LENGTH_LONG).show();
Log.v(TAG, "Get getTeleService...");
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService=(ITelephony) m.invoke(tm);
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG,
"FATAL ERROR: could not connect to telephony subsystem");
Log.e(TAG, "Exception object: " + e);
}
}
}
But the call is not ended even though i am able to print no. when outgoing call starts which show broadcasting receiver is working right .
Any suggestion
Yes definately there is two way to do it either using airplane mode or internal telephony for this . I used internal telephony and code I developed is uploaded here https://github.com/deependersingla/end_calls.
If you need anything more tell me , will be happy to help.
Following will give me basic wifi information, but I want the hardware information:
WiFiScanReceiver.java
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;
public class WiFiScanReceiver extends BroadcastReceiver {
private static final String TAG = "WiFiScanReceiver";
systemInfo systemInfo;
public WiFiScanReceiver(systemInfo systemInfo) {
super();
this.systemInfo = systemInfo;
}
#Override
public void onReceive(Context c, Intent intent) {
List<ScanResult> results = systemInfo.wifi.getScanResults();
ScanResult bestSignal = null;
for (ScanResult result : results) {
if (bestSignal == null
|| WifiManager.compareSignalLevel(bestSignal.level,
result.level) < 0) bestSignal = result;
}
String message = String.format(
"%s networks found. %s is the strongest.", results.size(),
bestSignal.SSID);
Toast.makeText(systemInfo, message, Toast.LENGTH_LONG).show();
Log.d(TAG, "onReceive() message: " + message);
}
}
systemInfo.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class systemInfo extends Activity implements OnClickListener {
private static final String TAG = "WiFiDemo";
WifiManager wifi;
BroadcastReceiver receiver;
TextView textStatus;
Button buttonScan;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
textStatus.append("\n\nWiFi Status: " + info.toString());
// List available networks
List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
textStatus.append("\n\n" + config.toString());
}
// Register Broadcast Receiver
if (receiver == null) receiver = new WiFiScanReceiver(this);
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Log.d(TAG, "onCreate()");
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
System.out.println("availableMegs:::::::::::" + availableMegs);
}
#Override
public void onStop() {
unregisterReceiver(receiver);
}
public void onClick(View view) {
Toast.makeText(this, "On Click Clicked. Toast to that!!!",
Toast.LENGTH_LONG).show();
if (view.getId() == R.id.buttonScan) {
Log.d(TAG, "onClick() wifi.startScan()");
wifi.startScan();
String ab = getInfo();
System.out.println("CPU INFORMATON:::::::::::::\n" + ab);
textStatus.append("CPU INFORMATON:::::::::::::\n" + ab);
}
}
private String getInfo() {
StringBuffer sb = new StringBuffer();
sb.append("abi: ").append(Build.CPU_ABI).append("\n");
if (new File("/proc/cpuinfo").exists()) {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(
"/proc/cpuinfo")));
String aLine;
while ((aLine = br.readLine()) != null) {
sb.append(aLine + "\n");
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
permissions are
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
This gives me basic wifi information .But I want the hardware information ..
One important difference is the CPU architecture. Although almost all Android devices use ARM CPU, it comes with different versions, including armv5, armv5te, armv6, armv6 with VFP, armv7, armv7 with VFP, armv7 with neon etc.
If your question is how to obtain the hardware information about the WiFi chip, then answer is simple: Android does not provide this kind of data, except of MAC address (which, btw, is not really the hardware information).
For some reason it doesn't like the getInetAddresses() method in the lines:
Enumeration additions = (Enumeration) ev.getInfo().getInetAddresses();
if (ev.getInfo().getInetAddresses() != null && ev.getInfo().getInetAddresses().length > 0) {
additions = ev.getInfo().getInetAddresses()[0].getHostAddress();
}
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import javax.jmdns.ServiceInfo;
private String type = "_workstation._tcp.local.";
private JmDNS jmdns = null;
private ServiceListener listener = null;
private ServiceInfo serviceInfo;
private void setUp() {
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
lock = wifi.createMulticastLock("mylockthereturn");
lock.setReferenceCounted(true);
lock.acquire();
try {
jmdns = JmDNS.create();
jmdns.addServiceListener(type, listener = new ServiceListener() {
#Override
public void serviceResolved(ServiceEvent ev) {
Enumeration additions = (Enumeration) ev.getInfo().getInetAddresses();
if (ev.getInfo().getInetAddresses() != null && ev.getInfo().getInetAddresses().length > 0) {
additions = ev.getInfo().getInetAddresses()[0].getHostAddress();
}
notifyUser("Service resolved: " + ev.getInfo().getQualifiedName() + " port:" + ev.getInfo().getPort() + additions);
}
#Override
public void serviceRemoved(ServiceEvent ev) {
notifyUser("Service removed: " + ev.getName());
}
#Override
public void serviceAdded(ServiceEvent event) {
// Required to force serviceResolved to be called again (after the first search)
jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
}
});
serviceInfo = ServiceInfo.create("_test._tcp.local.", "AndroidTest", 0, "plain test service from android");
jmdns.registerService(serviceInfo);
} catch (IOException e) {
e.printStackTrace();
return;
}
}
Try download and use latest version of JmDNS from Maven Central Repository, apparently there are some issues related to the jar file downloaded from their SourceForge home page. jar file from SourceForge doesn't play quite nice with Android.
Check out this SO question for more details. Hope this help.