I want when Click button in android studio make connection with python - android

I tried clicking on a button to make connection with python
but it doesn't run except it only run in main
This is the code that run the connection
public class link {
public static void main(String a[]) {
try {
Process p = Runtime.getRuntime().exec(
"python C:/Users/ASUS/Desktop/sendingCode/jaad/app/test.py");
Scanner in = new Scanner(new InputStreamReader(
p.getInputStream()));
String line = "";
while ((line = in.nextLine()) != null) {
// display each output line form python script
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Once I put the previous code on button it wont work with me i dont know why
recordBtn=(Button)findViewById(R.id.recordBtn);
recordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Process p = Runtime.getRuntime().exec(
"python C:/Users/ASUS/Desktop/sendingCode/jaad/app/test.py");
Scanner in = new Scanner(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = in.nextLine()) != null) {
// display each output line form python script
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
});

Related

(Android / React Native) Unable to list file system

Response always empty executing ls -a command with native modules.
Other commands like getprop or whoami work just fine tho.
Ive tried cd "other/dir" && ls -a, but also didn't work.
Does anyone know what I might be missing here?
Java / Native Module
#ReactMethod
public void executeCommand(final String command, final Callback callback) {
// To avoid UI freezes run in thread
new Thread(new Runnable() {
public void run() {
OutputStream out = null;
InputStream in = null;
try {
// Send script into runtime process
Process child = Runtime.getRuntime().exec(command);
child.waitFor();
// Get input and output streams
out = child.getOutputStream();
in = child.getInputStream();
// Input stream can return anything
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null){
result += line+"\n";
}
// Handle input stream returned message
callback.invoke(result);
} catch (Exception e) {
e.printStackTrace();
callback.invoke(e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}).start();
}
In the React world
import { NativeModules } from 'react-native';
const { AndroidShell } = NativeModules;
AndroidShell.executeCommand("ls -a", (res: string) => {
console.log(res)
});

Retrieve the saved WiFi passwords from Android devices

I am developing an Android application in which I need to show the saved WiFi passwords in the mobile or tablet. Like for example, if my mobile is connected to any network that n/w password is saved in my mobile. I want to get it.
Unless you are rooted, I don't know of any way to do it. If you are rooted, or are willing to root your Galaxy for those nice guy points, you should be able to use a file manager (ASTRO, Root Browser, etc.) to find it.
Use the file manager to locate your data/misc/file folder, then look for wpa_supplicant.conf, or I assume it could be wep_supplicant.conf if his/her network is using WEP instead of WPA. Open the .conf file using a text editor (which is probably built into your file manager application, if not, add that to your shopping list). You should be able to read the password in plain text at that point.
Your Comments helped me to some extent to find out the solution to my question. Especially #Namik Kalavadia I am talking about you Thanks for that.
Finally here is the solution.
public class MainActivity extends Activity {
File file;
public StringBuffer ab;
public File savefile;
public InputStream in = null;
public String filename = "wpa_supplicant.conf";
public File ot_path;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
ot_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.d("aaa", ""+ot_path.toString());
}
public void path(View v){
getPath();
}
private void getPath(){
file = Environment.getRootDirectory();
String ext = ".conf";
File list[] = file.listFiles();
ab = new StringBuffer();
if(list!=null){
fileNameSearch(list);
}
}
public void fileNameSearch(File list[]){
if(list!=null){
for(int f = 0;f<list.length;f++){
ab.append(list[f].getName()+"\n");
File fi = list[f];
String path = fi.getPath();
if(fi.isDirectory()){
fileNameSearch(fi.listFiles());
}
else if(path.endsWith(".conf")){
if(path.contains(filename)){
try{
File fileForParse = copyFile(path,ot_path);
in = new FileInputStream(fileForParse);
getStringFromInputStream(in);
Log.d("aaa", "conf I got it"+path);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
else{
Log.d("aaa", "List is null in method");
}
}
private File copyFile(String inputPath, File outputPath) {
InputStream input = null;
OutputStream out = null;
try {
if (!outputPath.exists())
{
outputPath.mkdirs();
}
savefile = new File(outputPath,filename);
if (!savefile.exists()) {
savefile.createNewFile();
File f = new File(inputPath);
Log.d("aaa",""+f.length());
input = new FileInputStream(inputPath);
out = new FileOutputStream(savefile);
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
Log.d("aaa",""+savefile.length());
input.close();
input = null;
out.flush();
out.close();
out = null;
}
} catch (FileNotFoundException fnfe1) {
Log.e("aaa", fnfe1.getMessage());
return null;
}
catch (Exception e) {
Log.e("aaa", e.getMessage());
return null;
}
return savefile;
}
#SuppressWarnings("deprecation")
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
if(line.contains("ssid")||line.contains("psk")){
sb.append(line+"\n");
}
if(line.contains("}")){
sb.append("-----------------\n");
}
AlertDialog ad = new AlertDialog.Builder(MainActivity.this).create();
ad.setTitle("Lis of WiFi Passwords Saved in your Mobile");
ad.setMessage(sb);
ad.setButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
ad.show();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
It is not possible as far as I know . It will be a security problem if sdk tools allows to do so .
Retrieving saved Wifi password programatically is not possible due to security issue.If you root your phone you may able to get it,but that too in an encrypted form.

Run bash script from android app

I want to change the value of variable in xml. The value is based on another file which read by editXml.sh. So I need to run the editXml.sh before app is compiled.
I try to run the script in MainActivity with code as follows:
onCreate() {
......
execScript();
}
execScript(){
try{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("sh /.../editXml.sh");
} catch(Throwable t)
{
t.printStackTrace();
}
}
The editXml.sh is in my local, but the code doesn't work when I run app in Android studio.(Works on local) Should I put my script in the app? And which part of the app? Any suggestion?
Try this. I've tested this code and it works.
Let's you script named script.sh.
Put file script.sh to you project's /res/raw folder.
Use code below.
Build apk. Unpack apk (this is usual zip-archive) and make sure file /res/raw/script.sh exists there.
Install apk on device and start it.
public static void executeCommandAndGetOutput(String command){
BufferedReader reader = null;
String result = "";
try {
Process p = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null)
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Log.i("Test", result);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String pathToScript = getDir("my_scripts", 0).getAbsolutePath() + File.separator + "script.sh";
// Unpacking script to local filesystem
InputStream in = getResources().openRawResource(R.raw.script);
FileOutputStream out = null;
try {
out = new FileOutputStream(pathToScript);
byte[] buff = new byte[1024];
int read = 0;
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
}
catch(Exception e){
}
finally {
try {
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Make script executable
executeCommand("chmod 775 " + pathToScript);
// Execute script
executeCommand("sh " + pathToScript);
}
public static String getSystemCommandOutput(String command){
BufferedReader reader = null;
String result = "";
try {
Process p = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(reader);
}
return result;
}
You can put script at raw resources and then unpack it to Context.getDir(...) folder and run from there with absolute path.
Also you need to run "chmod 775" (chmod +x) for this file before executing.
Example about copying a file from raw: Copying raw file into SDCard? You can copy to app folder (Context.getDir(...)) instead of sdcard
console output:
58:07.979 8935-8935/cc.softwarefactory.lokki.android E/MainActivity﹕ onCreate
12:58:08.234 8935-8935/cc.softwarefactory.lokki.android E/MainActivity﹕ PATH: /data/data/cc.softwarefactory.lokki.android/app_my_scripts/editxml.sh
12:58:08.258 8935-8935/cc.softwarefactory.lokki.android E/MainActivity﹕ result:
12:58:08.287 8935-8935/cc.softwarefactory.lokki.android E/MainActivity﹕ result: not found
I changed
Log.i("Test", result) to Log.e(TAG,"result: " + result);

make android source using adb shell command "cat"

I want to use shell command, 'cat'.
I want to copy the "abc.jpg" file..But It didn't operate.
What is the problem? Thank you.
public void onClick(View v) {
Runtime runtime = Runtime.getRuntime();
Process process;
try {
String cmd = "cat /sdcard/0/Pikicast/abc.jpg>/sdcard/0/apk_backups/abc.jpg";
process = runtime.exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
Log.i("test",line);
}
} catch (Exception e) {
e.fillInStackTrace();
Log.e("Process Manager", "Unable to execute top command");
}
}
I have modified your code a little. Kindly try this.
String[] command = {"cat","/sdcard/0/Pikicast/abc.jpg>/sdcard/0/apk_backups/abc.jpg"};
StringBuilder cmdReturn = new StringBuilder();
try {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
int c;
while ((c = inputStream.read()) != -1) {
cmdReturn.append((char) c);
}
prompt.setText(cmdReturn.toString());
Log.w("test",cmdReturn);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Process Manager", "Unable to execute top command");
}

Android AsyncTask send/read data using Socket

I'm working on a test project, something like a basic chat program using wi-fi connection.
I'm creating sockets to connect two different devices, but my problem is that when I send the first message, it's showing in the other device. But if I try to send again, I can see in the logs from the first one, that the message is sent, but it never shows up in the second device.
I've tried to implement the reading of the received data in another thread..or in Async Task, but the problem is still there. Here are both ways of my implementation :
Single Thread :
public void listenForSocket(){
thread = new Thread(new Runnable() {
public void run() {
Log.e("READDATAFROMSOCKET","READDATAFROMSOCKET");
try {
// sets the service running state to true so we can get it's state from other classes and functions.
serverSocket = new ServerSocket(DNSUtils.port);
client = serverSocket.accept();
client.setKeepAlive(true);
InputStream is = client.getInputStream();
Log.d("","is Size : "+is.available());
BufferedReader in = new BufferedReader(new InputStreamReader(is));
int readed = in.read();
Log.d("","readed bytes : "+readed);
String line = "";
while ((line = in.readLine()) != null) {
Log.i("","line : "+line);
changeText(line);
}
//client.close();
//serverSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
And here is AsyncTask :
class ServerTask extends AsyncTask<Void, Void, Void>{
private String line = "";
#Override
protected Void doInBackground(Void... params) {
try {
Log.e("ASYNCTASK","ASYNCTASK");
// sets the service running state to true so we can get it's state from other classes and functions.
serverSocket = new ServerSocket(DNSUtils.port);
client = serverSocket.accept();
client.setKeepAlive(true);
InputStream is = client.getInputStream();
Log.d("","is Size : "+is.available());
BufferedReader in = new BufferedReader(new InputStreamReader(is));
int readed = in.read();
Log.d("","readed bytes : "+readed);
while ((line = in.readLine()) != null) {
Log.i("","line : "+line);
}
//client.close();
//serverSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
changeText(line);
}
}
changeText(String); -
private void changeText(final String line) {
runOnUiThread(new Runnable() {
#Override
public void run() {
LinearLayout.LayoutParams params = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
TextView sendMsg = new TextView(MainActivity.this);
sendMsg.setText(DNSUtils.clientName+" : "+line);
sendMsg.setTextColor(Color.DKGRAY);
sendMsg.setTextSize(18);
layout.addView(sendMsg, params);
}
});
}
Any ideas how to fix this issue?
And another problem is that when I am reading the received data, the first letter of the sent string never shows. It always starts from the second letter.
Thanks in advance.
If i were you i will try to implement serverSocket = new ServerSocket(DNSUtils.port); only once with new; not in every thread.

Categories

Resources