Connecting to a Hidden Wi-Fi network in Android programmatically? - java

I am creating an Android application which should connect to a known available Hidden Wi-Fi network.
Which is the proper approach to handle this scenario ?
I have implemented trying to connect to a hidden wifi network. I tried on android devices with OS versions 6.0, 7.0, 7.1.1, 8.0 But couldn't achieve success.
fun initiateWifiConnectivity(mContext: Context, sSID: String, password: String) {
mWifiManager = mContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
if (!mWifiManager!!.isWifiEnabled) {
mWifiManager!!.isWifiEnabled = true
}
mWifiConfiguration = WifiConfiguration()
mWifiConfiguration!!.SSID = convertToQuotedString(sSID)
mWifiConfiguration!!.preSharedKey = password
mWifiConfiguration!!.status = WifiConfiguration.Status.ENABLED
mWifiConfiguration!!.hiddenSSID = true
mWifiConfiguration!!.allowedAuthAlgorithms.
set(WifiConfiguration.AuthAlgorithm.LEAP)
mWifiConfiguration!!.allowedGroupCiphers.
set(WifiConfiguration.GroupCipher.TKIP)
mWifiConfiguration!!.allowedGroupCiphers.
set(WifiConfiguration.GroupCipher.CCMP)
mWifiConfiguration!!.allowedGroupCiphers.
set(WifiConfiguration.GroupCipher.WEP40)
mWifiConfiguration!!.allowedKeyManagement.
set(WifiConfiguration.KeyMgmt.WPA_PSK)
mWifiConfiguration!!.allowedKeyManagement.
set(WifiConfiguration.KeyMgmt.WPA_EAP)
mWifiConfiguration!!.allowedKeyManagement.
set(WifiConfiguration.KeyMgmt.IEEE8021X)
mWifiConfiguration!!.allowedPairwiseCiphers.
set(WifiConfiguration.PairwiseCipher.TKIP)
mWifiConfiguration!!.allowedPairwiseCiphers.
set(WifiConfiguration.PairwiseCipher.CCMP)
mWifiConfiguration!!.allowedPairwiseCiphers.
set(WifiConfiguration.PairwiseCipher.NONE)
mWifiConfiguration!!.allowedProtocols.
set(WifiConfiguration.Protocol.RSN)
mWifiConfiguration!!.allowedProtocols.
set(WifiConfiguration.Protocol.WPA)
mWifiManager!!.addNetwork(mWifiConfiguration!!)
Handler().postDelayed(Runnable {
val list = mWifiManager!!.configuredNetworks
for (i in list) {
if (i.SSID != null && i.SSID ==
convertToQuotedString(sSID)) {
mWifiManager!!.disconnect()
mWifiManager!!.enableNetwork(i.networkId, true)
mWifiManager!!.reconnect()
break
}
}
}, 15000)
}

I connected a hidden WIFI network in Android Studio with a divice Android 7.0. Put the conf.hiddenSSID = true; of the object WifiConfiguration, the configuration to connect a network is similar to a notable network.
public class ShowActivity extends AppCompatActivity {
private WifiManager wifiManager; // Here is defined the instance
WifiConfiguration conf = new WifiConfiguration();
Log.d("Aut", Net + " : " + Pw);
conf.SSID = "\"" + Net + "\"";
conf.preSharedKey = "\"" + Pw + "\"";
conf.hiddenSSID = true; // Put this line to hidden SSID
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
// Connect Network
this.wifiManager =(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
assert wifiManager != null;
int netId = this.wifiManager.addNetwork(conf);
WifiInfo wifi_inf = this.wifiManager.getConnectionInfo();
this.wifiManager.disableNetwork(wifi_inf.getNetworkId());
this.wifiManager.enableNetwork(netId, true);
this.wifiManager.reconnect();
}

Related

How to check if the device is connected to internet and Connection type in Harmony Os

I was trying to check if the device is connected to internet and what is the network type. Here is an example of how we check it in android
public boolean isConnectingToInternet(Activity act){
boolean isthere = false;
TelephonyManager tm = (TelephonyManager) act.getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() != TelephonyManager.SIM_STATE_UNKNOWN){
ConnectivityManager connectivityManager = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED))
isthere = true;
} else {
ConnectivityManager connectivityManager = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED))
isthere = true;
}
return isthere;
}
Add permission ohos.permission.GET_NETWORK_INFO, which is used to obtain network information. Add permission ohos.permission.INTERNET, which is used to access the network.
• Check if network is connected
public static boolean hasInternetConnection(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED);
}
• Check if WiFi is connected
public static boolean isWifiConnectedInternet(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED) &&
netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI) ||
netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI_AWARE);
}
• Check if Mobile network is connected
public static boolean isMobileConnectedInternet(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED) &&
netCapabilities.hasBearer(NetCapabilities.BEARER_CELLULAR);
}
You could refer to this Docs to check the status of the connection to the Internet.
And the TelephonyConstants.NETWORK_TYPE_LTE can determine the network type.
// Obtain the RadioInfoManager object.
RadioInfoManager radioInfoManager = RadioInfoManager.getInstance(context);
// Obtain the signal information.
List<SignalInformation> signalList = radioInfoManager.getSignalInfoList(slotId);
// Check the size of the signal information list.
if (signalList.size() == 0) {
return;
}
// Traverse the signal information list to obtain the signal information of the current network type.
LteSignalInformation lteSignal = null;
for (SignalInformation signal : signalList) {
int signalNetworkType = signal.getNetworkType();
if (signalNetworkType == TelephonyConstants.NETWORK_TYPE_LTE) {
lteSignal = (LteSignalInformation) signal;
}
}
// Obtain the signal strength of the specified RAT (methods in the child class).
int signalLevel = lteSignal != null ? lteSignal.getSignalLevel() : 0;

Android management API service file allocation

I am testing android managment API using localhost as call back url. I followed each and every step following this url Android Management API Sample.
Now i m stuck on place.. according to this guide, i download the json file from service account. Now i copy that json file and save in app folder of my project.
This is my enterprise.json file
Screenshot of json file in android studio
and i just give folder location as enterprise.json in location string
This is my code
private static final String PROJECT_ID = "enterprise-271814";
private static final String SERVICE_ACCOUNT_CREDENTIAL_FILE =
"enterprise.json";
private static final String POLICY_ID = "samplePolicy";
/** The package name of the COSU app. */
private static final String COSU_APP_PACKAGE_NAME =
"com.ariaware.devicepoliceycontroller";
/** The OAuth scope for the Android Management API. */
private static final String OAUTH_SCOPE =
"https://www.googleapis.com/auth/androidmanagement";
private static final String APP_NAME = "Device Policey Controller";
private final AndroidManagement androidManagementClient;
public Sample(AndroidManagement androidManagementClient) {
this.androidManagementClient = androidManagementClient;
}
public void run() throws IOException {
// Create an enterprise. If you've already created an enterprise, the
// createEnterprise call can be commented out and replaced with your
// enterprise name.
String enterpriseName = createEnterprise();
System.out.println("Enterprise created with name: " + enterpriseName);
// Set the policy to be used by the device.
setPolicy(enterpriseName, POLICY_ID, getCosuPolicy());
// Create an enrollment token to enroll the device.
String token = createEnrollmentToken(enterpriseName, POLICY_ID);
System.out.println("Enrollment token (to be typed on device): " + token);
// List some of the devices for the enterprise. There will be no devices for
// a newly created enterprise, but you can run the app again with an
// existing enterprise after enrolling a device.
List<Device> devices = listDevices(enterpriseName);
for (Device device : devices) {
System.out.println("Found device with name: " + device.getName());
}
// If there are any devices, reboot one.
if (devices.isEmpty()) {
System.out.println("No devices found.");
} else {
rebootDevice(devices.get(0));
}
}
public static AndroidManagement getAndroidManagementClient()
throws IOException, GeneralSecurityException {
try (FileInputStream input =
new FileInputStream(SERVICE_ACCOUNT_CREDENTIAL_FILE)) {
GoogleCredential credential =
GoogleCredential.fromStream(input)
.createScoped(Collections.singleton(OAUTH_SCOPE));
return new AndroidManagement.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
credential)
.setApplicationName(APP_NAME)
.build();
}
}
private String createEnterprise() throws IOException {
// Initiate signup process.
System.out.println("Creating signup URL...");
SignupUrl signupUrl =
androidManagementClient
.signupUrls()
.create()
.setProjectId(PROJECT_ID)
.setCallbackUrl("https://localhost:9999")
.execute();
System.out.print(
"To sign up for a new enterprise, open this URL in your browser: ");
System.out.println(signupUrl.getUrl());
System.out.println(
"After signup, you will see an error page in the browser.");
System.out.print(
"Paste the enterpriseToken value from the error page URL here: ");
String enterpriseToken =
new BufferedReader(new InputStreamReader(System.in)).readLine();
// Create the enterprise.
System.out.println("Creating enterprise...");
return androidManagementClient
.enterprises()
.create(new Enterprise())
.setProjectId(PROJECT_ID)
.setSignupUrlName(signupUrl.getName())
.setEnterpriseToken(enterpriseToken)
.execute()
.getName();
}
private Policy getCosuPolicy() {
List<String> categories = new ArrayList<>();
categories.add("android.intent.category.HOME");
categories.add("android.intent.category.DEFAULT");
return new Policy()
.setApplications(
Collections.singletonList(
new ApplicationPolicy()
.setPackageName(COSU_APP_PACKAGE_NAME)
.setInstallType("FORCE_INSTALLED")
.setDefaultPermissionPolicy("GRANT")
.setLockTaskAllowed(true)))
.setPersistentPreferredActivities(
Collections.singletonList(
new PersistentPreferredActivity()
.setReceiverActivity(COSU_APP_PACKAGE_NAME)
.setActions(
Collections.singletonList("android.intent.action.MAIN"))
.setCategories(categories)))
.setKeyguardDisabled(true)
.setStatusBarDisabled(true);
}
private void setPolicy(String enterpriseName, String policyId, Policy policy)
throws IOException {
System.out.println("Setting policy...");
String name = enterpriseName + "/policies/" + policyId;
androidManagementClient
.enterprises()
.policies()
.patch(name, policy)
.execute();
}
private String createEnrollmentToken(String enterpriseName, String policyId)
throws IOException {
System.out.println("Creating enrollment token...");
EnrollmentToken token =
new EnrollmentToken().setPolicyName(policyId).setDuration("86400s");
return androidManagementClient
.enterprises()
.enrollmentTokens()
.create(enterpriseName, token)
.execute()
.getValue();
}
private List<Device> listDevices(String enterpriseName) throws IOException {
System.out.println("Listing devices...");
ListDevicesResponse response =
androidManagementClient
.enterprises()
.devices()
.list(enterpriseName)
.execute();
return response.getDevices() ==null
? new ArrayList<Device>() : response.getDevices();
}
private void rebootDevice(Device device) throws IOException {
System.out.println(
"Sending reboot command to " + device.getName() + "...");
Command command = new Command().setType("REBOOT");
androidManagementClient
.enterprises()
.devices()
.issueCommand(device.getName(), command)
.execute();
}
Moreover i m using android management api for the first time and i dont know its proper implementation. Anyone who has experience on this kinllt guide me a little bit. I found a lot about this but i didn't found any userful tutorial
For Android, you have to store the service account file either in the assets folder or raw folder.
This thread provides code on a number of ways to load the json data into an InputStream depending on the location you selected.

Why android hides bluetooth mac address?

i'm trying to get bluetooth mac address in this way:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String address = mBluetoothAdapter.getAddress();
But it always returns:
02:00:00:00:00:00
Why? Is it a kind of security policy?
Thanks.
Giacomo
Maybe you should check out this answer.
Snippet from answer:
private String getBluetoothMac(final Context context) {
String result = null;
if (context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH)
== PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Hardware ID are restricted in Android 6+
// https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-hardware-id
// Getting bluetooth mac via reflection for devices with Android 6+
result = android.provider.Settings.Secure.getString(context.getContentResolver(),
"bluetooth_address");
} else {
BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
result = bta != null ? bta.getAddress() : "";
}
}
return result;
}

How to Set wifi proxy Hostname, port and bypass programmatically in Android 5.0 and above

I want to set wifi proxy hostname, port and bypass programmatically. i follow this link ->How can I set ProxySettings and ProxyProperties on Android Wi-Fi connection using Java?. but that code is not working on Android 5.0.2. Is there any other way to set those settings?
Tested.. Its working in Android 5.1.0, Dont forget to add permissions
WifiConfiguration GetCurrentWifiConfiguration(WifiManager manager)
{
if (!manager.isWifiEnabled())
return null;
List<WifiConfiguration> configurationList = manager.getConfiguredNetworks();
WifiConfiguration configuration = null;
int cur = manager.getConnectionInfo().getNetworkId();
for (int i = 0; i < configurationList.size(); ++i)
{
WifiConfiguration wifiConfiguration = configurationList.get(i);
if (wifiConfiguration.networkId == cur)
configuration = wifiConfiguration;
}
return configuration;
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void setWifiProxySettings5()
{
//get the current wifi configuration
WifiManager manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiConfiguration config = GetCurrentWifiConfiguration(manager);
if(null == config)
return;
try
{
//linkProperties is no longer in WifiConfiguration
Class proxyInfoClass = Class.forName("android.net.ProxyInfo");
Class[] setHttpProxyParams = new Class[1];
setHttpProxyParams[0] = proxyInfoClass;
Class wifiConfigClass = Class.forName("android.net.wifi.WifiConfiguration");
Method setHttpProxy = wifiConfigClass.getDeclaredMethod("setHttpProxy", setHttpProxyParams);
setHttpProxy.setAccessible(true);
//Method 1 to get the ENUM ProxySettings in IpConfiguration
Class ipConfigClass = Class.forName("android.net.IpConfiguration");
Field f = ipConfigClass.getField("proxySettings");
Class proxySettingsClass = f.getType();
//Method 2 to get the ENUM ProxySettings in IpConfiguration
//Note the $ between the class and ENUM
//Class proxySettingsClass = Class.forName("android.net.IpConfiguration$ProxySettings");
Class[] setProxySettingsParams = new Class[1];
setProxySettingsParams[0] = proxySettingsClass;
Method setProxySettings = wifiConfigClass.getDeclaredMethod("setProxySettings", setProxySettingsParams);
setProxySettings.setAccessible(true);
ProxyInfo pi = ProxyInfo.buildDirectProxy("127.0.0.1", 8118);
//Android 5 supports a PAC file
//ENUM value is "PAC"
//ProxyInfo pacInfo = ProxyInfo.buildPacProxy(Uri.parse("http://localhost/pac"));
//pass the new object to setHttpProxy
Object[] params_SetHttpProxy = new Object[1];
params_SetHttpProxy[0] = pi;
setHttpProxy.invoke(config, params_SetHttpProxy);
//pass the enum to setProxySettings
Object[] params_setProxySettings = new Object[1];
params_setProxySettings[0] = Enum.valueOf((Class<Enum>) proxySettingsClass, "STATIC");
setProxySettings.invoke(config, params_setProxySettings);
//save the settings
manager.updateNetwork(config);
manager.disconnect();
manager.reconnect();
}
catch(Exception e)
{
Log.v("wifiProxy", e.toString());
}
}

Send MMS from My application in android

I want to send MMS from my application to a specific number. I've searched and found this code but I have no idea if this code what I need or not.
My Questions is :
-can anyone explain this code to me.i am beginner in MMS.
-also, i thought this code is let the user send MMS from my application without move it to the native Messaging inbox (and this is what i want) Am i right?
-also i have a problem ,i do not know how can i put this code in my project.
this is what i found
MMS is just a http-post request. You should perform the request using extra network feature :
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final int result = connMgr.startUsingNetworkFeature( ConnectivityManager.TYPE_MOBILE, Phone.FEATURE_ENABLE_MMS);
If you get back the result with Phone.APN_REQUEST_STARTED value, you have to wait for proper state. Register BroadCastReciver and wait until Phone.APN_ALREADY_ACTIVE appears:
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(reciver, filter);
If background connection is ready, then build content and perform request. If you want to do that using android's internal code, please use this:
final SendReq sendRequest = new SendReq();
final EncodedStringValue[] sub = EncodedStringValue.extract(subject);
if (sub != null && sub.length > 0) {
sendRequest.setSubject(sub[0]);
}
final EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipient);
if (phoneNumbers != null && phoneNumbers.length > 0) {
sendRequest.addTo(phoneNumbers[0]);
}
final PduBody pduBody = new PduBody();
if (parts != null) {
for (MMSPart part : parts) {
final PduPart partPdu = new PduPart();
partPdu.setName(part.Name.getBytes());
partPdu.setContentType(part.MimeType.getBytes());
partPdu.setData(part.Data);
pduBody.addPart(partPdu);
}
}
sendRequest.setBody(pduBody);
final PduComposer composer = new PduComposer(this.context, sendRequest);
final byte[] bytesToSend = composer.make();
HttpUtils.httpConnection(context, 4444L, MMSCenterUrl, bytesToSendFromPDU, HttpUtils.HTTP_POST_METHOD, !TextUtils.isEmpty(MMSProxy), MMSProxy, port);
MMSCenterUrl: url from MMS-APNs,
MMSProxy: proxy from MMS-APNs,
port: port from MMS-APNs
Note that some classes are from internal packages. Download from android git is required.
The request should be done with url from user's apn-space code:
public class APNHelper {
public class APN {
public String MMSCenterUrl = "";
public String MMSPort = "";
public String MMSProxy = "";
}
public APNHelper(final Context context) {
this.context = context;
}
public List<APN> getMMSApns() {
final Cursor apnCursor = this.context.getContentResolver().query(Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"), null, null, null, null);
if ( apnCursor == null ) {
return Collections.EMPTY_LIST;
} else {
final List<APN> results = new ArrayList<APN>();
while ( apnCursor.moveToNext() ) {
final String type = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.TYPE));
if ( !TextUtils.isEmpty(type) && ( type.equalsIgnoreCase(Phone.APN_TYPE_ALL) || type.equalsIgnoreCase(Phone.APN_TYPE_MMS) ) ) {
final String mmsc = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSC));
final String mmsProxy = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPROXY));
final String port = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPORT));
final APN apn = new APN();
apn.MMSCenterUrl = mmsc;
apn.MMSProxy = mmsProxy;
apn.MMSPort = port;
results.add(apn);
}
}
apnCursor.close();
return results;
}
Please help me
why don't you use the android system functions:
Please have a look on
https://developer.android.com/guide/components/intents-common.html
public void composeMmsMessage(String message, Uri attachment) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("smsto:")); // This ensures only SMS apps respond
intent.putExtra("sms_body", message);
intent.putExtra(Intent.EXTRA_STREAM, attachment);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent); }
}
Cheers
Tom
I found a link in an other thread to a github project that works 100% https://github.com/klinker41/android-smsmms
Notice, that obligatory settings are only
Settings sendSettings = new Settings();
sendSettings.setMmsc(mmsc);
sendSettings.setProxy(proxy);
sendSettings.setPort(port);
you can get them something like (found at Set APN programmatically on Android - answear by vincent091):
Cursor cursor = null;
if (Utils.hasICS()){
cursor =SqliteWrapper.query(activity, activity.getContentResolver(),
Uri.withAppendedPath(Carriers.CONTENT_URI, "current"), APN_PROJECTION, null, null, null);
} else {
cursor = activity.getContentResolver().query(Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"),
null, null, null, null);
}
cursor.moveToLast();
String type = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.TYPE));
String mmsc = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSC));
String proxy = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSPROXY));
String port = cursor.getString(cursor.getColumnIndex(Telephony.Carriers.MMSPORT));

Categories