hey guys,
Building an app that runs a ping command at the moment and I can't quite get it to work. If I modify the command to something that isn't a terminal command then it'll output my error statement but i can't get it to display the ping output. any help would be awesome. I know my outputs for my error are bad but it's an easy way to determine what path it's outputting.
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.lang.Process;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView Text = new TextView(this);
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.getRuntime().exec("system/bin/ping 192.168.1.1");
BufferedReader in = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line = "null";
while ((line = in.readLine()) != null) {
Text.setText(in.readLine());
}
}
catch (Exception e)
{
String line="55";
Text.setText(line);
}
setContentView(Text);
}
}
Thanks for any help you guys can give me,
Adam
Hey,
Try using "system/bin/ping -c 1 192.168.1.1" instead.
And then add this line just after that:
Code:
proc.waitFor();
and while reading the output of the ping you might want to do it like this maybe?
Code:
String line = "";
String result = "";
while (line != null)
{
result = result + "\n" + line;
line = in.readLine();
}
Text.setText(result);
If you want to ping more than 1 packet I think it would be better to make a new thread and do proc.waitFor() in that thread. Then send a message using a handler to set the output of the ping to the TextView
k i have done that and that does make more sense but Im still getting a black screen on the output. i am testing on a Sony tab s and using AIDE (on the device) cause my eclipse is broken. this is how my code looks now,
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.lang.Process;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView Text = new TextView(this);
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.getRuntime().exec("system/bin/ping 192.168.1.1");
BufferedReader in = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line = "null";
while ((line = in.readLine()) != null) {
Text.setText(in.readLine());
}
}
catch (Exception e)
{
String line="55";
Text.setText(line);
}
setContentView(Text);
}
}
Is there anything else I could be missing??
Thanks,
Adam
Hey, I think you posted the same code again.
I am not sure if you can read the process stream before it is complete and ping does take a long time to complete. So your main thread is blocking on it and it doesn't get to executing the setContentView.
Thats why I think going for a seperate thread is a better option.
so it would be better to put the ping into a new class and call on it when i need it??
Not a seperate class, a seperate thread to be more specific.
Even if you do put the ping code in a seperate class' method and call that method in onCreate it will still run on the your applications main thread.
What I was trying to say is something along the lines of the following code:
Code:
private TextView textView;
private Process process;
private Handler handler;
private Thread pingThread;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
textView = new TextView(this);
textView.setText("Pinging...");
setContentView(textView);
try
{
process = Runtime.getRuntime().exec("system/bin/ping -c 5 192.168.1.1");
handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
String result = "";
while(line != null)
{
result = result + "\n" + line;
line = reader.readLine();
}
reader.close();
textView.setText(result);
}
catch(Exception e)
{
e.printStackTrace();
textView.setText("Error");
}
}
};
pingThread = new Thread()
{
@Override
public void run()
{
try
{
process.waitFor();
}
catch(Exception e)
{
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
};
pingThread.start();
} catch (Exception e)
{
e.printStackTrace();
}
}
I am not sure if this is exactly how you want your app to behave. There might be a better way of doing what you want than what I have suggested but I tested the above code and it works for me.
thats wicked, basically what want my program to do is to run a ping command through a usb to rj45 adapter. at the moment I just need it to do the ping command through wifi and once that was working I was going to set it up to go through usb.
I wonder if there's something I'm doing wrong like I'm build the apk in AIDE on the tablet or something, cause I'm still getting a black screen when booting the app.
If I error the code up a bit, Like put "system/bin/pi ....." instead I do get pinging on the app but no error output and if the code is fine then nothing displays
That is very strange :S.
If you use the incorrect command it works fine but when you use the correct command it doesn't?
Can you post your code? or provide more details if possible?
the code is just the code you posted cause I thought if a I could get it working with that code then modify it to what it needs to do, when the command is incorrect it displays "ping....." but doesn't display an error, I'm going to install eclipse and build the package with that and see how it goes. did you test on a tablet and what did you use to deploy the package?
Adz117 said:
the code is just the code you posted cause I thought if a I could get it working with that code then modify it to what it needs to do, when the command is incorrect it displays "ping....." but doesn't display an error, I'm going to install eclipse and build the package with that and see how it goes. did you test on a tablet and what did you use to deploy the package?
Click to expand...
Click to collapse
I think i know whats happening. It isnt the Ide and using eclipse wont make much of a difference.
Are you usIng something like -c 5 in the ping command? Cause if you aren't i think ping is Going to take a really long time and all you'll see on the screen is "Pinging..."
Yea I have got that in the command, when the code is correct and working I dont get anything all I get is a black screen. Its when I error the command up a bit that I get pinging
Sent from my Sony Tablet S using XDA
hey guys,
just got eclipse running and tested it on an avd emulator and it runs perfect, so the question is what would cause it not to run on my tablet?
I have no idea! I don't have access to an Android Tablet, so I can't test it out! I tested it out on my phone too and it works just fine.
One thing I can suggest though is:
Put log statements throughout the program to signify where the the control has reached. Then run it on your tablet. That should shed some light on where the code is failing on your tablet.
tested it on my phone which is running 2.3 and it failed on there as well, "ping......" would pop up for about a second then disappear, also if I use a command like ls instead of ping on my tablet it will work perfectly fine so I'm guessing for some reason past android 2.1 it doesn't like the ping command. any ideas?
I tested it out on phone with 2.2. Did you try putting log statements and checking where it is failing.
You could also add breakpoints in your code and run it?
I have been working on a Home Screen widget for the past two days. The widget's `onUpdate()` method calls a service which fetches RSS information (title and image link) using `XmlPullParser`. These are working properly by printing the value in `LogCat`.
I want to set the text in the `TextView (tv1)` of AppWidget and image link as image to the `ImageView (imv1)` and a `TextView (go11)` clickable to open the browser and goto the link. I put the following in `OnStart()` just to test the SetText.
Code:
RemoteViews rv = new RemoteViews(this.getApplicationContext().getPackageName(),R.layout.main);
// Set the text
rv.setTextViewText(R.id.tv1,"WORKED");
Its not working. Second, I tried to set the image by:
Code:
InputStream is = (InputStream) new URL(imglnk).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
rv.setImageViewResource(R.id.imv1, 0);
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
rv.setImageViewBitmap(R.id.imv1,bitmap);
Where imglnk is the link to the image. ImageView is not showing the image.
Then I tried to set the OnClick listener to open the browser with google as a test.
Code:
RemoteViews rv1 = new RemoteViews("com.example.axstartup",R.layout.main);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
PendingIntent pi = PendingIntent.getActivity(context, 0, browserIntent,PendingIntent.FLAG_UPDATE_CURRENT);
rv1.setOnClickPendingIntent(R.id.go11, pi);
Even that is not working. Please help me with this.
I work at a small company that fields autonomous android devices which programmatically connect to bluetooth telemetry devices. These devices require pins, so we need to automatically create a pairing in order to connect to the bluetooth devices. We DO have root access.
Since the new Bluetooth Stack in Android 4.2, I have been unable to use this common AIDL bluetooth reflection method in our private utility app:
Code:
public IBluetooth getIBluetooth() {
IBluetooth ibt = null;
try {
Class c2 = Class.forName("android.os.ServiceManager");
Method m2 = c2.getDeclaredMethod("getService",String.class);
IBinder b = (IBinder) m2.invoke(null, "bluetooth");
Class c3 = Class.forName("android.bluetooth.IBluetooth");
Class[] s2 = c3.getDeclaredClasses();
Class c = s2[0];
Method m = c.getDeclaredMethod("asInterface",IBinder.class);
m.setAccessible(true);
ibt = (IBluetooth) m.invoke(null, b);
} catch (Exception e) {
}
return ibt;
}
The issue about this strategy no longer working is documented here. I previously used the setPin method as well as the createBond method from this Interface, and now I cannot.
Is there anyway to manually create a bluetooth pair profile under Android 4.2? Is there a database file where the profiles are stored that we can use root and sqlite3 to access?
Jelly Bean (Android 4.2) access to hidden methods.
I posted this on Stack Overflow:
http://stackoverflow.com/questions/14705167/how-connect-paired-bluetooth-a2dp-device-on-android-4-2-using-reflection/16003953#16003953
It explains how I got it working. This open source project:
http://code.google.com/p/a2dp-connect2/
Implemented this approach and it works on API 17. Mt project only accesses methods through IBluetoothA2dp and IBluetooth but others should work in a similar fashion.
Hi!
I am trying to develop an android app with a google map v2, location service and some control buttons.
But I don't want to put all these things inside one MainActivity class. So I thought I could split all the code into some more classes. The MainActivity shall controll all the GUI things and react on map or location events...
Now I have the following problem. Inside my onCreate I instanziate the additional classes:
Code:
// Preferences as singleton
pref = Prefs.getInstance(this.getApplicationContext());
pref.loadSettings();
// Set up the location
loc = new Locations(pref);
loc.setCallback(this);
map = new MyMap(pref);
It seems to work fine. But inside the MyMap class every time I start the app a null pointer exception is thrown. When I am calling MyMap() the following code will be executed:
Code:
[...]
private Prefs pref;
private GoogleMap mMap;
[...]
public MyMap(Prefs prefs) {
pref = (Prefs) prefs;
if (mMap == null) {
FragmentManager fmanager = getSupportFragmentManager();
mMap = ((SupportMapFragment) fmanager.findFragmentById(R.id.map)).getMap();
[...]
}
The line with the findFragmentById is the one that causes the exception.
If I write
Code:
SupportMapFragment f = ((SupportMapFragment) fmanager.findFragmentById(R.id.map));
f is allways null. But how can I access the fragments and view elements defined within my MainActivity?
It works if I put the code inside my MainAcitivity.
Every class extends "android.support.v4.app.FragmentActivity"
I tried to save the application context within my Prefs() class, so that I can access it from everywhere.
But I don't know how to use it inside my additional classes.
How to share the "R" across all my classes?
Can someone help me please?
Thank you very much!!
Thorsten
Are you having trouble adding a Map to a Fragment? If so, then you may take a look at this tutorial. I haven't tried it myself since I couldn't install Google Play Services on my development device. If it helps, do write back, as I am definitely going to try it myself soon.
More information like this, you can visit HUAWEI Developer Forum
What is SafetyDetect?
SafetyDetect is an API or Kits that provide security checks to your application. This will help to protect your app against security threats or malicious programs.
The kits consists of 5 main APIs:
SysIntegrity API: Checks whether the device running your app is secure, for example, whether it is rooted.
AppsCheck API: Obtains a list of malicious apps.
URLCheck API: Determines the threat type of a specific URL.
UserDetect API: Checks whether your app is interacting with a fake user.
WifiDetect API: Checks whether the Wi-Fi to be connected is secure.
Why SafetyDetect?
Why do you want to use safetydetect?
Imagine that if your app deals with sensitive data and/or provide transactional capabilities, you would not want your app security to be compromised.
SafetyDetect will provide the security (device, url, apps, wifi) to your app so that you can ensure that your app and data is not compromised when infected device access your apps.
Using SysIntegrity API
To use SysIntegrity API, there are only a few simple steps.
First, add the required app gallery plugin and safety detect dependency to your build.gradle
Project build.gradle:
Code:
dependencies {
implementation 'com.huawei.hms:safetydetect:{version}'
}
Module build.gradle:
Code:
implementation 'com.huawei.hms:safetydetect:5.0.1.300'
Next, to call the API you will need to generate a nonce value, this value must be at least 16 bytes and is only valid once. This value will be returned also within the SafetyDetect response, so you can use this value to check the validity of the Response.
A nonce can be the app username appended with the timestamp of the request, or any unique value of the application.
Code:
fun invokeSysIntegrityCheck() {
val mClient = SafetyDetect.getClient(this)
val nonce = "This Is Just A Test Nonce".toByteArray(Charsets.UTF_8)
val task = mClient.sysIntegrity(nonce, "your app id")
task.addOnSuccessListener {res ->
// sys integrity call success, result is returned
val result = res.result
}.addOnFailureListener {
// something went wrong, please check your app id and if you have enabled the safety detect api in developer console
it.printStackTrace()
}
}
The result of the check is returned in a json format, sample is below:
Code:
{
"advice":"RESTORE_TO_FACTORY_ROM",
"apkCertificateDigestSha256":[
"yT5JtXRgeIgXssx1gQTsMA9GzM9ER4xAgCsCC69Fz3I="
],
"apkDigestSha256":"6Ihk8Wcv1MLm0O5KUCEVYCI/0KWzAHn9DyN38R3WYu8=",
"apkPackageName":"com.huawei.hms.safetydetectsample",
"basicIntegrity":false,
"nonce":"R2Rra24fVm5xa2Mg",
"timestampMs":1571708929141
}
If the basicIntegrity parameter is false, the user device is at risk. You can choose to notify the user or block the access of the app if you think it’s necessary.
Using AppsCheck API
AppsCheck api is a service where it will detect if any malicious apps are installed on the device. The signature of this malicious apps is stored in the cloud and is periodically updated.
Code:
fun invokeAppsCheck() {
val mClient = SafetyDetect.getClient(this)
val task = mClient.maliciousAppsList
task.addOnSuccessListener {
// service call is successful. we will need to check the app lsit response to see if there is any malicious app installed
val appDataList = it.maliciousAppsList
if (it.rtnCode == CommonCode.OK) {
if (appDataList.isEmpty()){
// malicious apps list is empty, device is safe.
}
else {
// malicious apps is detected on the device
appDataList.forEach {
Log.w("warn", "Malicious app detected: ${it.apkCategory}, ${it.apkPackageName}, ${it.apkSha256}")
}
}
}
}.addOnFailureListener {
// something went wrong
}
}
Using URLCheck API
URLCheck is a service which allows the app to check a particular URL for malicious URL. This is very useful for app that re-directs the user to a lot of other 3rd party URL, such as barcode scanner.
To use URL Check Api:
Code:
fun doUrlCheck(url: String) {
val mClient = SafetyDetect.getClient(this)
// Check the URL
// Param1: URL To be checked
// Param2: your Huawei App ID
// Param3&4: Types of threat to be checked
mClient.urlCheck(url, "your app id here",
UrlCheckThreat.MALWARE,
UrlCheckThreat.PHISHING)
.addOnSuccessListener {
if (it.urlCheckResponse.isEmpty()) {
// No threat or phishing detected
} else {
// Threat detected
}
}
}
So there we have it. Safety Detect is really useful to secure your apps from threats when user is using the app.
For more information, please see the developer link:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050156325