I've tried connecting to an API running locally on my machine to retrieve values in an Android emulator.
I keep getting 404 Error. Any idea what should be done here for the API? Thank you for your help.
var test = "";
var url = "http://10.0.2.2:60002/api/values/" + Convert.ToInt32(Id);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{user}:{pass}")));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var response = await client.GetStringAsync(url);
test = response;
}
return test;
use 127.0.0.1 as the ip address. It should solve the problem.
If not,
type "adb shell ifconfig" or "adb shell ipaddr" in your command prompt.
(once of them should work)
Check if your either one of your machine's ip adresses are there. If there is a matching one use it.
To check your machine's ipaddress,
If you are using windows
Type ipconfig in your command prompt.
If you are using Linux
Type ifconfig in your shell.
Related
Working on a Go project and using gomobile to generate .apk file.
I am trying to open a browser in the go code with a passing URL.
I know go supports running CMD commands in different operating systems such as windows and Linux.
Wonder to know if there is any code to support Android OS as well.
In other words in following code what should I have under
case "android":
func openbrowser(url string) {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
if err != nil {
log.Fatal(err)
}
}
You can try using ADB Shell. Check this question Need command line to start web browser using adb
adb shell am start -a android.intent.action.VIEW -d 'http://stackoverflow.com/?uid=isme\&debug=true'
I'm trying to run a shell command in my Android app in order to check if a give tcp port is opened or not:
Runtime.getRuntime().exec(arrayOf("/system/bin/sh", "-c", "netstat -tulpn | grep :8080"))
Running this command in Android version < 10, works fine. It will do a full scan and return the entry if there is the given port used.
But in Android 10, it is not working anymore. The process exec will return:
Process[pid=9534 ,hasExited=true, exitcode=1]
When reading the inputStream of the process it is always null, while executing netstat -tulpn | grep :8080 from terminal will return an entry, as expected.
Running
Runtime.getRuntime().exec(arrayOf("/system/bin/sh", "-c", "netstat -tulpn"))
alone, and parsing the output, will only show:
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program Name
and no other data at all.
I only have this problem in Android 10, because for older versions it is working.
Has anything changed in Android 10 regarding to shell commands? It is necessary for me to run this command.
Any help would be appreciated...
This is most likely because of privacy protection improved in Android 10.
Look here: https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem
My goal was to check if a given tcp port was in use or not. I made this method that did the job that I was looking for:
private fun isPortUsed(port: Int): Boolean {
return try {
// Try to open socket at the given port
val socket = ServerSocket(port)
// Release port
socket.close()
false
} catch (ex: BindException) {
// Port is already in use
true
} catch (ex: Exception) {
// Other reason for failing
false
}
}
I am really new to AWS and EC2, and I am trying to hook my Android project with my new Parse server hosted on my EC2 instance but in order to initialize my server in my project, I need my APP_ID and CLIENT_KEY which for some silly reason I cannot find them.
Here is what I have done till now:
I am Not using a Java SSH Client since It doesn't working! Instead I am using the alternative which is a standalone SSH client
Connected to bitnami parse server via my terminal (Mac), with success.
I obtained my username and password and I have access to my Parse dashboard.
Most suggestions I came across, where giving solutions based on a Java SSH client via Browser connection, but like I said, I am using the Standalone one. So how do I obtain it??
Here is my code:
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
//where do I Find my APP_ID
.applicationId("myappid")
//where do I Find my CLIENT_KEY
.clientKey(null)
.server("http://ec2-xx-xxx-xxx-xx.us-east-2.compute.amazonaws.com/parse/")
.build()
);
ParseObject object = new ParseObject("ExampleObject");
object.put("myNumber", "123");
object.put("myString", "rob");
object.saveInBackground(new SaveCallback () {
#Override
public void done(ParseException ex) {
if (ex == null) {
Log.i("Parse Result", "Successful!");
} else {
Log.i("Parse Result", "Failed" + ex.toString());
}
}
});
Turnes out all I had to do was to open the server.js file on the Bitnami parse server running in my terminal. And that's achieved by doing the following (In the Bitnami parse server in Terminal):
cd /opt/bitnami/apps/parse/htdocs/
and then:
vi server.js
This problem usually occurs while using putty in Windows 10, so if you want to open the server.js file in the terminal, you have to run the following commands:
cd stack/parse
cat config.json
And if you want to know your username and password for logging in Parse Dashboard, you have to run the following command:
cat /home/bitnami/bitnami_credentials
Here is the link where you can check all the commands that are mentioned above int the console:
just run this below command
ssh -i <your pem file with path> <your public DNS>
for example
sudo ssh -i "Downloads/karthi.pem" ubuntu#ec2-1821-434-234-5130.us-east-2.compute.amazonaws.com
I too faced the same problem while using PuTTY on my Windows 10. Then I posted this issue on Udemy platform of my course. There Rob (Tutor of course) replied with the following way.
cd stack/parse
cat config.json
Hope this works for you too.the following link is the code how it worked for me. Check it if you want
When my Android device (Samsung galaxy s4) is connected to my laptop (Windows 7), I would like to be able to access files on the Android device from the Windows 7 command line. The commands :
cd Computer\GGS4\Phone
or
Computer\GGS4\Phone:
don’t work
FYI, the reason why I need this is to use mp3slpt from laptop to cut mp3 file on the Android device.
Something like :
D:\temp> mp3splt Computer\GGS4\Podcast\program1.mp3 7.12 7.30 -d out -o program1Extract
Newer Android devices (primarily) use MTP to communicate with USB hosts. Older devices were identified as mass storage devices. Win7 supports MTP but it doesn't "mount" the device as a drive and the device storage is therefore not available via a file path.
I think the best solution is to copy the file before passing it to mp3splt:
adb pull Podcast/program1.mp3
mp3splt program1.mp3 7.12 7.30 -d out -o program1Extract
del program1.mp3
You can also develop a Win7 driver that provides a virtual drive using MTP or run an FTP server on your device which you can then associate with a Windows drive (native Win7 example).
You can try to install a WebDAV server to the android device, then mount the WebDAV server as a drive on Windows 7, after mounting to a drive, you can access the drive (android folder) from the command line.
Here is a free WebDAV server from Google Play (Of course, there are many other WebDAV servers in Google Play)
And the steps to mount the WebDAV server as a drive on Windows 7
On your Android device:
Settings->More Settings...->USB Utilities
Press "Connect storage to PC" button and plug USB cable.
Then press "Turn on USB Storage" and you will see new Drive Letter in My Computer assigned to your Phone.
Now you can run ur command:
D:\temp> mp3splt DRIVE_LETTER:\Podcast\program1.mp3 7.12 7.30 -d out -o program1Extract
I post this as answer considering its high view count relative to similar questions, coming from popuplar search engines.m sorry to post this as answer because I'm unable to verify if this really works on Win7, but it certainly is an answer for the same question for Win10 using PowerShell: https://github.com/nosalan/powershell-mtp-file-transfer/
PowerShell and the Shell.Application object that is relied upon were already available back in 1999 (see this blog post https://www.computerperformance.co.uk/powershell/com-shell/) , so I believe it can work on Win7.
Disclaimer: I'm not the author of the script, so credits belong to him.
Just for this answer, I copied and pasted code snippets from the linked source to provide it with some explanation.
The trick to access the phone, which should be in "File transfer" mode when connected through USB, is in this part:
$phoneName = "Nokia 7.2"
$o = New-Object -com Shell.Application
$rootComputerDirectory = $o.NameSpace(0x11)
$phoneDirectory = $rootComputerDirectory.Items() | Where-Object {$_.Name -eq $phoneName} | select -First 1
Then you are able to traverse to the directory you want:
$sourceFolder = $phoneDirectory
$phoneFolderName = "Internal shared storage\DCIM\Camera"
foreach($pathSegment in ($phoneFolderName -split "\\"))
{
$sourceFolder = $sourceFolder.GetFolder.Items() | Where-Object {$_.Name -eq $pathSegment} | select -First 1
if($sourceFolder -eq $null)
{
throw "Not found $phoneFolderName folder"
}
}
And finally copy items from the reached sourceFolder to the destination:
function Get-FullPathOfMtpDir($mtpDir)
{
$fullDirPath = ""
$directory = $mtpDir.GetFolder
while($directory -ne $null)
{
$fullDirPath = -join($directory.Title, '\', $fullDirPath)
$directory = $directory.ParentFolder;
}
return $fullDirPath
}
$targetFolder = "E:\Test"
$destDirShell = (new-object -com Shell.Application).NameSpace($targetFolder)
$fullSourceDirPath = Get-FullPathOfMtpDir $sourceFolder
foreach ($item in $sourceFolder.GetFolder.Items())
{
$itemName = ($item.Name)
$fullFilePath = Join-Path -Path $targetFolder -ChildPath $itemName
if(Test-Path $fullFilePath)
{
Write-Host "Element '$itemName' already exists"
}
else
{
$copiedCount++;
Write-Host ("Copying #{0}: {1}{2}" -f $copiedCount, $fullSourceDirPath, $item.Name)
$destDirShell.CopyHere($item)
}
}
Write-Host "Copied '$copiedCount' elements from '$fullSourceDirPath'"
It's also possible to copy files back to the phone. Here I swap the target and source as example, and copy "E:\Test\atestfileonpc.txt" to the phone's "DCIM\Camera" folder:
$sourceDirShell = (new-object -com Shell.Application).NameSpace($targetFolder)
$targetDirShell = $sourceFolder
$item = $sourceDirShell.Items() | Where-Object {$_.Name -eq "atestfileonpc.txt"} | select -First 1
targetDirShell.GetFolder.CopyHere($item)
Pros of this method, is that you don't have to install any additional software on your phone or your Win10 (or Win7 ?) pc. Cons for your question, you have to copy files from phone to your pc, use mp3splt on them, and copy the results back.
Can anyone say, whether adb commands can be executed through my android application. If it is possible to execute, how it can be implemented?
You can do it with this:
Process process = Runtime.getRuntime().exec("your command");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
Don't forget to surround it with a try and catch statement.
Edit:
#Phix is right, ProcessBuilder would be better to use.
Normal Android apps have different privileges to processes started via adb, e.g., processes started via adb are allowed to the capture the screen whereas normal apps aren't. So, you can execute commands from your app via Runtime.getRuntime().exec(), but they won't have the same privileges as if you had executed from an adb shell.
i came across this post looking for a different query, but i have worked specifically with input on android before, so I'd just like to put some clarity on the matter.
The reason why
Runtime.getRuntime().exec("adb shell input keyevent 120");
Is not working, is because you are not removing
adb shell
The ADB part is only for use on your computer, if you have incorrectly installed ADB, the command would actually be a path to the adb.exe file on your computer, like this
C:\XXXX\ADB Files\adb.exe shell
or
C:\XXXX\ADB Files\adb shell
The shell part tells the ADB program on your computer to access the devices shell, so your device will not know what shell is either...
Using sh /path/to/commandList.sh will execute the commads listed in commandList.sh as it is a shell script (a .batch file on windows is similar )
The command you want to use is
Runtime.getRuntime().exec("input keyevent 120");
However this will cause Environment null and working directory null, you can bypass this by writing the commands to a shell script ( .sh file ) and then running the script with
Runtime.getRuntime().exec("sh path/to/shellScript.sh");
Sometimes the sh is not needed, but i use it just incase.
I hope this clears at least something up :)
adb shell invoked in Runtime.getRuntime().exec is not running under shell user. It provide shell but with same process owner user (like u0_a44). That's the reason all command did not work.
This is what I do in Kotlin, I also get command responses too
fun runShellCommand(command: String) {
// Run the command
val process = Runtime.getRuntime().exec(command)
val bufferedReader = BufferedReader(
InputStreamReader(process.inputStream)
)
// Grab the results
val log = StringBuilder()
var line: String?
line = bufferedReader.readLine()
while (line != null) {
log.append(line + "\n")
line = bufferedReader.readLine()
}
val Reader = BufferedReader(
InputStreamReader(process.errorStream)
)
// if we had an error during ex we get here
val error_log = StringBuilder()
var error_line: String?
error_line = Reader.readLine()
while (error_line != null) {
error_log.append(error_line + "\n")
error_line = Reader.readLine()
}
if (error_log.toString() != "")
Log.info("ADB_COMMAND", "command : $command $log error $error_log")
else
Log.info("ADB_COMMAND", "command : $command $log")
}
Executing
Runtime.getRuntime().exec("adb shell input keyevent 120");
I got the following error:
java.io.IOException: Cannot run program "adb": error=13, Permission denied.
Executing
Runtime.getRuntime().exec("adb shell input keyevent 120");
There is no error but at the same time, my request is not processed to take the screenshot.
I found out this was working in earlier versions of android but later it was removed. Though I'm not able to provide the source here why it is not working.
Hope this helps someone like me who is trying to use this approach to take the screenshot when the app is not in the foreground.
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
string cmd = "/system/bin/input keyevent 23\n";
os.writeBytes(cmd);
the phone must be rooted. here I have executed adb command "input keyevent 23".
remember when you execute adb command through su you does not need to add "adb shell input keyevent 23"