[Q] Get active Wifi connection information - Android Studio

Hello everyone,
I am making an app for android, in this I need to know some data of the active wifi connection, such as network type and encryption used, as shown in the image.
Information as if WEP, WPA, WPA2 and TKIP or AES encryption
I tried with android.net.wifi and within wificonfiguration classes and their different methods, they return me a set of information, but is not always valid, however as shown by the android itself in the properties of the connection if is true forever.
Thank you very much.
Att,
Cristhian Angarita
Colombia, Bogota

Most probably you have already found answer: currentWifi.getSSID() is quoted in most cases where scanResult.SSID is not (and of course you must not use == on strings ).
Try something like this, it returns current SSID or null:
Code:
public static String getCurrentSsid(Context context) {
String ssid = null;
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) {
ssid = connectionInfo.getSSID();
}
}
return ssid;
}
also permissions are required:
Code:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
StringUtil is not a standard Android class, so you can use TextUtils instead. The code then looks like this:
Code:
public static String getCurrentSsid(Context context) {
String ssid = null;
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo.isConnected()) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
ssid = connectionInfo.getSSID();
}
}
return ssid;
}
bye

Related

Please help with Java homework!!!

Okay here's the thing:
I have an assignment in Java class that's due in 1.5 hours and figured that this would be the best place to ask since you guys are (hopefully) good at this kind of stuff.
Here's the code:
/**
* Exercise 3.
*
* Complete the setBalances method below to set all accounts in an array to the specified value.
*
* The test methods should pass.
*
*/
public class AccountMethods {
public static void main(String[] args) {
Account[] accounts = {new Account(100, "joe"),
new Account(200, "jane"),
new Account(300, "jerry")};
testSetBalances(accounts, 50);
testBalanceNonNegative();
}
public static void setBalances(Account[] accounts, double value) {
double balance = 0;
for (int i = 0; i < accounts.length; i++) {
balance += accounts.getBalance();
}
}
public static boolean testSetBalances(Account[] accounts, double value) {
setBalances(accounts, value);
for (int i = 0; i < accounts.length; i++) {
if (accounts.getBalance() != value) {
System.out.println("testSetBalances fails on element " + i);
return false;
}
}
System.out.println("testSetBalances passes.");
return true;
}
public static boolean testBalanceNonNegative() {
Account a = new Account(100, "jim");
a.setBalance(-100);
if (a.getBalance() < 0) {
System.out.println("testBalanceNonNegtaive fails");
return false;
} else {
System.out.println("testBalanceNonNegative passes.");
return true;
}
}
}
The bold part is what I'm suppose to be working with, but I can't get it to pass in the testSetBalances method. I don't know if I'm explaining this right, but when I'm compiling the code, it's suppose to say:
testSetBalances passes
But instead, it's saying: testSetBalances fails on element 0
Don't worry about the other parts of the code because the assignment for that is done already.

I'd like to decrease dialer vibration and I need help with that..

I'm completely noob.
Here are the sources
http://grepcode.com/file/repository...cFeedback.java#HapticFeedback.0mHapticPattern
Code:
public void init(Context context, boolean enabled) {
mEnabled = enabled;
if (enabled)
{
mVibrator = new SystemVibrator(context);
mHapticPattern = new long[] {0, DURATION, 2 * DURATION, 3 * DURATION};
mSystemSettings = new Settings.System();
mContentResolver = context.getContentResolver();
}
}
I need to change mHapticPattern array to adjust vibration duration on dialpad.
So, I can use that
Code:
findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "init", new XC_MethodHook()
{
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// BUT I don't know what I have to write here to get it working :(
// I know that this method will be called after init method and I don't know how I can change mHapticPattern array :(
}
});
Or I think I can also change value of Duration
private static final long DURATION = 10;
Click to expand...
Click to collapse
But anyway I do not know how...
I will be glad if anyone will try to help me...
Changing DURATION directly will have no effect. This is because the compiler replaces final static variables with their values (so "10" will be directly used instead of "DURATION").
What you could do is replace the init(Context context, boolean enabled) method entirely. Check out the development tutorial (and other wiki pages) for some hints on where to get started.
GermainZ said:
Changing DURATION directly will have no effect. This is because the compiler replaces final static variables with their values (so "10" will be directly used instead of "DURATION").
What you could do is replace the init(Context context, boolean enabled) method entirely. Check out the development tutorial (and other wiki pages) for some hints on where to get started.
Click to expand...
Click to collapse
Thank you for your answer. But I did not see it till now. That's why my respond is so late.
I had one experience with replacing entire method. But it was just a boolean method. I used this example http://forum.xda-developers.com/showpost.php?p=34609860&postcount=4
And also I've tried to replace whole init method but I have a problem with that string:
Code:
mVibrator = new SystemVibrator(context);
I did
import android.os.SystemVibrator;
but this "android.os.SystemVibrator;" is highlighted with red in eclipse
It says "The import android.os.SystemVibrator cannot be resolved" but the file exists...
I have a code but because of that error I can't test it
S0bes said:
It says "The import android.os.SystemVibrator cannot be resolved" but the file exists...
Click to expand...
Click to collapse
It's possible it's not in the SDK. Use XposedHelpers.findClass(...) to get the SystemVibrator class, then XposedHelpers.newInstance(...) to create a new instance.
@GermainZ please help me. This is the last thing I want to implement. Dialpad vibration is heavy and I think it's not good for vibro inside my phone.
This is what I try but Vibration is gone after that:
PHP:
package com.s0bes.fmspeaker;
import android.content.Context;
import android.os.Vibrator;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import static de.robv.android.xposed.XposedHelpers.findClass;
import static de.robv.android.xposed.XposedHelpers.newInstance;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import android.content.ContentResolver;
import android.provider.Settings;
//import android.os.SystemVibrator;
public class bool1 {
static Context context;
private static Vibrator mVibrator ;
private static Settings.System mSystemSettings;
private static ContentResolver mContentResolver;
private static long[] mHapticPattern;
public static void InitResources(final LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals("com.android.dialer")) {
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader,
"init", Context.class, boolean.class, new XC_MethodHook() {
@Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable {
XposedBridge.log("HOOOKED init" );
//context=(Context) param.args[0];
}
});
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "init", Context.class, boolean.class, new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
context=(Context) param.args[0];
XposedBridge.log("REPLACED init. Enabled="+param.args[1] );
Class Myclass = findClass("android.os.SystemVibrator", lpparam.classLoader);
Object mVibrator = newInstance(Myclass, context);
mHapticPattern = new long[] {0, 10, 2 * 10, 8 * 10};
mSystemSettings = new Settings.System();
mContentResolver = context.getContentResolver();
return true;
}
});
}
}
}
EDIT:
Yeehoooo. I got this working
Your post http://forum.xda-developers.com/showpost.php?p=54951841&postcount=8 very helped me.
Instead replace init method I replaced vibrate();
PHP:
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "vibrate", new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
Class Myclass = findClass("android.os.SystemVibrator", lpparam.classLoader);
Object mVibrator = newInstance(Myclass, context);
mHapticPattern = new long[] {0, 10, 1 * 10, 1 * 10};
((Vibrator) mVibrator).vibrate(mHapticPattern, -1);
return true;
}
});
}

Location Returns Null

Good day!
Hello! Every time I try to get my location using Google Maps in my Android application, it returns "null" or doesn't get my location.
If I test my code with Mock Locations, which grants the statement "if ( myLocation != null ){}" the code works.
But the statement "if ( myLocation == null ){}" doesn't do anything.
Help is greatly appreciated.
Code:
@Override
public void onMapReady(GoogleMap googleMap) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
}, 10);
}
return;
}
gMap = googleMap;
if(!gMap.isMyLocationEnabled())
gMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
if(myLocation != null) {
LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 14), 1500, null);
//LONG CODE THAT CONTAINS GOOGLE MAP MARKERS. POLYLINES, RADIUS, Location.distanceBetween() statements
}
Hello,
The GPS on your device must be enabled. You could redirect your users to offer them to enable GPS and then when they will be back on your screen, you should be able to get a location.
Sylvain

Module stops working as soon as I load a native library (Please help)

Hi,
First, a disclaimer.
I am a Java and xposed noob. My background is in embedded C development so I can get by with some simple Java code and thanks to the great tutorials online I have been able to put together an xposed module but I'm struggling with a problem that is beyond my abilities now and am reaching out to the community for help.
Next, the background.
I have an Android head unit in my car. There is an app that provides me with CarPlay functionality but none of the controls on the steering wheel work with the app. When I analysed the code I found that they handle all of their button inputs using proprietary methods that do not inject an event into any input streams. I wrote an xposed module to hook the button press methods and then inject a proper input into one of the event streams.
Initially I tried to use the command line 'input' command to do this but since it is a Java app and takes about 1s to load it was too slow. My only other option was to create a virtual device on an input stream that I could then use to inject keypresses through the hooked method. To create a virtual device I needed to write C code that my xposed module would be able to access through the JNI. Long story short, after some pain I was able to get the native library integrated into the project and compiling using the NDK.
Finally, the problem.
When I was using the module without the native library it worked but just with a large delay because of the time it takes to load the 'input' java app. I was able to see logs from the module in the logcat as I hooked the method and as I went through the various actions within the hook.
As soon as I introduce the native library though the entire xposed module just stops running completely. I do not get any logs from the module even though I have installed, activated and rebooted. It shows up in the xposed installer but it just does nothing. The funny thing is that this happens even if I make no reference whatsoever to any native functions within the library. All I need to do to kill the module is to build it with the System.loadlibrary line in the Main.java uncommented. As soon as I comment that piece of code out the module starts to hook the function and output logs again. Below is the code from the Main.Java that I am referring to. I am happy to make any manifest, C and gradle files available too. Looking for any ideas as to why the module dies completely as soon as I include this...
Code:
package projects.labs.spike.zlink_xposed_swc;
import de.robv.android.xposed.XposedBridge;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import de.robv.android.xposed.XposedHelpers;
import android.app.AndroidAppHelper;
import android.content.Intent;
import android.os.Bundle;
import android.content.Context;
/* shellExec and rootExec methods */
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import android.view.KeyEvent;
import android.media.AudioManager;
public class Main implements IXposedHookLoadPackage {
public static final String TAG = "ZLINK_XPOSED ";
public static void log(String message) {
XposedBridge.log("[" + TAG + "] " + message);
}
//public native int CreateVirtualDevice();
//public native int SendPrev();
@Override
public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
log("handleLoadPackage: Loaded app: " + lpparam.packageName);
if (lpparam.packageName.equals("com.syu.ms")) {
findAndHookMethod("module.main.HandlerMain", lpparam.classLoader, "mcuKeyRollLeft", new XC_MethodHook() {
@Override
protected void afterHookedMethod(XC_MethodHook.MethodHookParam param) throws Throwable {
// previous
log("PREVKEYHIT");
//rootExec("input keyevent 88");
log("EVENTSENT");
//Below was trying to use media keys which zlink never responded to...
/* Context context = (Context) AndroidAppHelper.currentApplication();
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
mAudioManager.dispatchMediaKeyEvent(event);
KeyEvent event2 = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
mAudioManager.dispatchMediaKeyEvent(event2);*/
//Below is the failed broadcast intent method...
/*Context mcontext = (Context) AndroidAppHelper.currentApplication();
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mcontext.sendBroadcast(i);*/
}
});
}
}
public static String rootExec(String... strings) {
String res = "";
DataOutputStream outputStream = null;
InputStream response = null;
try {
Process su = Runtime.getRuntime().exec("su");
outputStream = new DataOutputStream(su.getOutputStream());
response = su.getInputStream();
for (String s : strings) {
s = s.trim();
outputStream.writeBytes(s + "\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
res = readFully(response);
} catch (IOException e) {
e.printStackTrace();
} finally {
Closer.closeSilently(outputStream, response);
}
return res;
}
public static String readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString("UTF-8");
}
[COLOR="Red"] static {
System.loadLibrary("native-lib");
}[/COLOR]
}
The issue with native library is quite strange and I cannot help with it as my experience with native libs is zero.
But maybe try a different method of injecting media key events.
Create a method:
Code:
void injectKey(int keyCode) {
try {
final long eventTime = SystemClock.uptimeMillis();
final InputManager inputManager = (InputManager)
mContext.getSystemService(Context.INPUT_SERVICE);
int flags = KeyEvent.FLAG_FROM_SYSTEM;
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 50, KeyEvent.ACTION_DOWN,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 25, KeyEvent.ACTION_UP,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
} catch (Throwable t) {
// something went wrong
XposedBridge.log(t.getMessage());
}
}
Then just do: injectKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
And maybe try playing with different KeyEvent flags and attrs.
Thanks so much for this suggestion! Any idea if this injects at a java level or if it depends on there being a keyboard input device available on one of the /dev/input/eventX streams? The android device that I am using has no keyboard available on any of those input streams. Will give it a try nonetheless
C3C076 said:
The issue with native library is quite strange and I cannot help with it as my experience with native libs is zero.
But maybe try a different method of injecting media key events.
Create a method:
Code:
void injectKey(int keyCode) {
try {
final long eventTime = SystemClock.uptimeMillis();
final InputManager inputManager = (InputManager)
mContext.getSystemService(Context.INPUT_SERVICE);
int flags = KeyEvent.FLAG_FROM_SYSTEM;
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 50, KeyEvent.ACTION_DOWN,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
XposedHelpers.callMethod(inputManager, "injectInputEvent",
new KeyEvent(eventTime - 50, eventTime - 25, KeyEvent.ACTION_UP,
keyCode, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, flags,
InputDevice.SOURCE_KEYBOARD), 0);
} catch (Throwable t) {
// something went wrong
XposedBridge.log(t.getMessage());
}
}
Then just do: injectKey(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
And maybe try playing with different KeyEvent flags and attrs.
Click to expand...
Click to collapse
looxonline said:
Thanks so much for this suggestion! Any idea if this injects at a java level or if it depends on there being a keyboard input device available on one of the /dev/input/eventX streams? The android device that I am using has no keyboard available on any of those input streams. Will give it a try nonetheless
Click to expand...
Click to collapse
Simply use whatever InputDevice that you think should work in your case.
The method basically calls this:
https://android.googlesource.com/pl.../android/hardware/input/InputManager.java#869
which is then propagated to Input Manager Service here:
https://android.googlesource.com/pl...oid/server/input/InputManagerService.java#598
which then calls nativeInjectInputEvent

How to get the address/name of connected Bluetooth device - Android

I need to get the CONNECTED device name and address.
This is what I have tried so far and with it I'm able to get the paired devices list and addresses.
'''
public class MainActivity extends AppCompatActivity {
TextView mBlue;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBlue = (TextView) findViewById(R.id.Bluetooth);
String s = " ";
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
Set <BluetoothDevice> devices = ba.getBondedDevices();
if (ba != null) {
for (BluetoothDevice device: devices)
s += device.getName() + "-" + device.getAddress() + "\n";
} else
s += "No address";
mBlue.setText(s.toString());
}
}
'''
How to get the device address/name of connected Bluetooth device?
Please help me out with a clear code (both manifest and class code). I have seen other posts on SO but I can't make it out. Please help to solve this.

Categories

Resources