Remove password and connect with new password wifi android - wifi

i would like to ask your help, this is my code :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==REQUEST_CODE_INPUT){
switch (resultCode){
case RESULT_CODE_PASS:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager wifiManager= (WifiManager) getSystemService(Context.WIFI_SERVICE);
pass=data.getStringExtra("passWord");
nameWifi=data.getStringExtra("nameWifi");
WifiConfiguration conf=new WifiConfiguration();
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
List<ScanResult> networkList=wifiManager.getScanResults();
if(networkList !=null){
for(ScanResult network : networkList){
if(network.SSID.startsWith("\"")){
network.SSID=network.SSID.substring(1, network.SSID.length() - 1);
}
if(nameWifi.equals(network.SSID)){
String Capabilities=network.capabilities;
if(Capabilities.contains("WPA2")){
conf.preSharedKey="\""+pass+"\"";
}else if(Capabilities.contains("WEP")){
conf.wepKeys[0]="\""+pass+"\"";
conf.wepTxKeyIndex=0;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
}
break;
}
}
}
wifiManager.addNetwork(conf);
List<WifiConfiguration> list=wifiManager.getConfiguredNetworks();
for(WifiConfiguration i: list){
if(i.SSID!=null && i.SSID.equals("\""+nameWifi+"\"")){
wifiManager.disconnect();
showWaiting();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
if(networkInfo.isConnected()){
dismissWaiting();
}else{
AlertDialog.Builder alert=new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Wrong Password")
.setMessage("Please try again")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.create().show();
}
}
}
break;
}
}
}
i have 2 Activities (MainActivity and ShareWifi), i create Sharewifi with purpose: users input wifi SSID and password then press Enter, both of them will send to MainActivity--> disable current wifi and reconnect with new password but it still uses old password to reconnect. I write this code follow this link : How do I connect to a specific Wi-Fi network in Android programmatically?
Please help me to resolve this problem. Thank you very much.

Resolved: add saveConfiguration and it works
wifiManager.addNetwork(conf);
wifiManager.saveConfiguration();

Related

Is it possible to switch wifi networks in Appium?

While executing my test suite I have to switch between different wifi networks available in Android Device.
In the middle of the execution I have to change my wifi connection from Wifi_Network_1 to Wifi_Network_2 provided ssid name and password of wifi network is known. How can it be done?
I am using:
Appium server -->1.8.1
java-client --> 6.1.0
selenium-java --> 3.13.0
Since NetworkConnectionSetting has been deprciated, I am not able to find alternate for it.
I can toggle wifi on/off using
driver.toggleWifi();
But it is not suitable for my case as i need to toggle between different wifi network available using SSID name and its password.
Thanks in advance.
Hi I'am using this method due Appium deprecated their switch for wifi, and I've created my own override via console via commands from adb. It is working for me so give it a try:
public synchronized boolean wifiSetup(String udid, boolean flg) {
synchronized (this) {
String flgEnabled = (flg) ? "enable" : "disable";
List<String> output = Console.runProcess(false, "adb -s " + udid + " shell am broadcast -a io.appium.settings.wifi --es setstatus " + flgEnabled);
for (String line : output) {
System.err.println(line);
if (line.equalsIgnoreCase("Broadcast completed: result=-1"))
return true;
}
return false;
}
}
usage to switch off:
wifiSetup("xxxUDIDfromAndroid", false);
usage to switch on:
wifiSetup("xxxUDIDfromAndroid", true);
And here is part for calling console:
public class Console {
private static final String[] WIN_RUNTIME = { "cmd.exe", "/C" };
private static final String[] OS_LINUX_RUNTIME = { "/bin/bash", "-l", "-c" };
private Console() {
}
private static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
#SuppressWarnings({ "hiding"})
private static <String> String[] concatStr(String[] first, String[] second) {
String[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public static List<String> runProcess(boolean isWin, String... command) {
String[] allCommand = null;
try {
if (isWin) {
allCommand = concat(WIN_RUNTIME, command);
} else {
allCommand = concat(OS_LINUX_RUNTIME, command);
}
ProcessBuilder pb = new ProcessBuilder(allCommand);
pb.redirectErrorStream(true);
Process p = pb.start();
p.waitFor();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String _temp = null;
List<String> line = new ArrayList<String>();
while ((_temp = in.readLine()) != null) {
// system.out.println("temp line: " + _temp);
line.add(_temp);
}
// system.out.println("result after command: " + line);
return line;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Hope this helps,

Result code for sharing intent for instagram android

Result code always gives 0 if i successfully shared an image with instagram via intent. Please help. Thanks in advance.
I have tried a lot.
This is my code :
File imageFileToShare = new File(filePath);
Uri uri = Uri.fromFile(imageFileToShare);
Intent shareInstagramIntent = new Intent(Intent.ACTION_SEND);
shareInstagramIntent.setPackage("com.instagram.android");
shareInstagramIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareInstagramIntent.setType("image/*");
shareInstagramIntent.putExtra(Intent.EXTRA_TEXT, text);
startActivityForResult(shareInstagramIntent, INSTAGRAM);
This is my onActivityResult :
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case INSTAGRAM:
logI("Request e: " + resultCode);
if (resultCode == thisActivity.RESULT_OK) {
Utilities.showAlert(thisActivity, "Image shared with instagram successfully");
new PostPointsTask("instagram").execute("");
} else {
Utilities.showAlert(thisActivity, "Image shared with instagram was cancelled");
}
}
}
There is no callback from instagram for share intent ,better use instagram sdk to share your message.

Deferring persistence as device is being used in BlackBerry when listening file change

I tried to listen file change event in BlackBerry base on FileExplorer example, but whenever I added or deleted file, it always showed "Deferring persistence as device is being used" and I can't catch anything .Here is my code:
public class FileChangeListenner implements FileSystemJournalListener{
private long _lastUSN; // = 0;
public void fileJournalChanged() {
long nextUSN = FileSystemJournal.getNextUSN();
String msg = null;
for (long lookUSN = nextUSN - 1; lookUSN >= _lastUSN && msg == null; --lookUSN)
{
FileSystemJournalEntry entry = FileSystemJournal.getEntry(lookUSN);
// We didn't find an entry
if (entry == null)
{
break;
}
// Check if this entry was added or deleted
String path = entry.getPath();
if (path != null)
{
switch (entry.getEvent())
{
case FileSystemJournalEntry.FILE_ADDED:
msg = "File was added.";
break;
case FileSystemJournalEntry.FILE_DELETED:
msg = "File was deleted.";
break;
}
}
}
_lastUSN = nextUSN;
if ( msg != null )
{
System.out.println(msg);
}
}
}
Here is the caller:
Thread t = new Thread(new Runnable() {
public void run() {
new FileChangeListenner();
try {
Thread.sleep(5000);
createFile();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
Create file method worked fine:
private void createFile() {
try {
FileConnection fc = (FileConnection) Connector
.open("file:///SDCard/newfile.txt");
// If no exception is thrown, then the URI is valid, but the file
// may or may not exist.
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and output:
0:00:44.475: Deferring persistence as device is being used.
0:00:46.475: AG,+CPT
0:00:46.477: AG,-CPT
0:00:54.476: VM:+GC(f)w=11
0:00:54.551: VM:-GCt=9,b=1,r=0,g=f,w=11,m=0
0:00:54.553: VM:QUOT t=1
0:00:54.554: VM:+CR
0:00:54.596: VM:-CR t=5
0:00:55.476: AM: Exit net_rim_bb_datatags(291)
0:00:55.478: Process net_rim_bb_datatags(291) cleanup started
0:00:55.479: VM:EVTOv=7680,w=20
0:00:55.480: Process net_rim_bb_datatags(291) cleanup done
0:00:55.481: 06/25 03:40:41.165 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
0:00:55.487: 06/25 03:40:41.171 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
I also tried to remove the thread or create or delete file in simulator 's sdcard directly but it doesn't help. Please tell me where is my problem. Thanks
You instantiate the FileChangeListenner, but you never register it, and also don't keep it as a variable anywhere. You probably need to add this call
FileChangeListenner listener = new FileChangeListenner();
UiApplication.getUiApplication().addFileSystemJournalListener(listener);
You also might need to keep a reference (listener) around for as long as you want to receive events. But maybe not (the addFileSystemJournalListener() call might do that). But, you at least need that call to addFileSystemJournalListener(), or you'll never get fileJournalChanged() called back.

how to check internet connection in java in blackberry

I want to check whether internet connection is there or not in blackberry device so that depending on the result I can call webservices to get data or upload data from my application
I have tried this one
CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS))) ||
(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) != false
If you want to check the internet connection, then send any url to the web service and check the HTTP Response. If HTTPResponse is 200 then only you are having internet connection. Do like this.......
try
{
factory = new HttpConnectionFactory();
url="Here put any sample url or any of your web service to check network connection.";
httpConnection = factory.getHttpConnection(url);
response=httpConnection.getResponseCode();
if(response==HttpConnection.HTTP_OK)
{
callback(response);
}else
{
callback(response);
}
} catch (Exception e)
{
System.out.println(e.getMessage());
callback(0);
}
Here "response"=200 then you have an internet connection. otherwise it is a connection problem. You can check this like below...........
public void callback(int i)
{
if(i==200)
{
//You can do what ever you want.
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
int k=Dialog.ask(Dialog.D_OK,"Connection error,please check your network connection..");
if(k==Dialog.D_OK)
{
System.exit(0);
}
}
});
}
}
Here System.exit(0); exit the application where ever you are.
Take these two classes
1)HttpConnectionFactory.java
2)HttpConnectionFactoryException.java
from this link:HttpConnection Classes

Critical tunnel failure error blackberry

I have developed a app for blackberry ,its approved from appworld but it gives following error
on 4.6
Critical tunnel failure
and
on 5.0 and 6.0
ava.io APN not specified
please help why this error is coming and how to solve it
I think Problem is you didn't add appropriate connection suffix to the url.
Follow the link can solve your problem:http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800451/800563/What_Is_-_Different_ways_to_make_an_HTTP_or_socket_connection.html?nodeid=826935&vernum=0
And also ou can use the following sample code:
private static String getConnectionString(){
String connectionString="";
if(WLANInfo.getWLANState()==WLANInfo.WLAN_STATE_CONNECTED){
connectionString=";interface=wifi";
}
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS){
connectionString = ";deviceside=false";
}
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT)==CoverageInfo.COVERAGE_DIRECT){
String carrierUid=getCarrierBIBSUid();
if(carrierUid == null) {
connectionString = ";deviceside=true";
}
else{
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
}
return connectionString;
}
Just to clear up some issues.
#Jisson your answer was helpful
But you did not include code for the method getCarrierBIBSUid()
/**
* Looks through the phone's service book for a carrier provided BIBS network
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid()
{
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for(currentRecord = 0; currentRecord < records.length; currentRecord++)
{
if(records[currentRecord].getCid().toLowerCase().equals("ippp"))
{
if(records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
{
return records[currentRecord].getUid();
}
}
}
return null;
}
Also it might be helpful to include
if (DeviceInfo.isSimulator()){
return ";deviceSide=true";
}
At the beginning of the getConnectionString() method
For more info see Melick's Blog
Solved this issue by setting the APN values on the phone its self and using the connection string code suggested in the other answers.
Change your APN settings (in South Africa)
On Home screen, click Options
Click Advanced Options and then TCP
Enter the APN: **internet**
username: **guest**
password: **guest**
Press the Menu key and select Save
(for rest of the world find your settings here)
From http://www.blackberrytune.com/blackberry-tcp-ip-apn-settings/
and
http://www.blackberryfaq.com/index.php/Carrier_specific_APN/TCP_settings

Resources