I am trying to make a VPN Service work on android.
To do this, I think I have to use the Builder class provided in the VpnService class, which is provided by the android SDK. Now when I try to do this, the method
builder.establish()
returns null. Here is the full method I wrote;
// If theInterface still exists from last time, reuse it, it has the same parameters.
if (theInterface != null) {
return;
}
// configure the VPN settings.
Builder builder = new Builder();
builder.setMtu(1500);
builder.addAddress("10.0.2.0", 32);
builder.addRoute("0.0.0.0", 0);
try {
theInterface.close();
} catch (Exception e) {
// Ignore
}
theInterface = builder.establish();
Log.i(TAG + "IMPORTANT", builder.toString());
The code crashes at:
Log.i(TAG + "IMPORTANT", builder.toString());
When debugging, the debugger says 'theInterface = null' throughout the entire execution of the program.
EDIT:
I have looked trough the Builder class which is located in android.net.VpnService
In this class, it seems that there is a hidden class (IConnectivityManager), maybe my problem has something to do with this...
Here is the piece of code I'm talking about.
/**
* Use IConnectivityManager since those methods are hidden and not
* available in ConnectivityManager.
*/
private static IConnectivityManager getService() {
return IConnectivityManager.Stub.asInterface(
ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
}
as VpnService.Builder.establish documents:
Returns ParcelFileDescriptor of the VPN interface, or null if the
application is not prepared.
need call VpnService.prepare: http://developer.android.com/reference/android/net/VpnService.html#prepare(android.content.Context) first
Related
I'm running this code with a Twitter handle I'm pretty sure doesn't exist in order to test error handling. The breakpoints on the Callback are never hit, neither for success nor failure.
Any pointers on why this is?
Just as a note, this code works fine with a valid Twitter handle, but doesn't call the Callback either.
final Callback<Tweet> actionCallback = new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
int x = 1;
x++; // This code is just so I can put a breakpoint here
}
#Override
public void failure(TwitterException exception) {
DialogManager.showOkDialog(context, R.string.twitter_feed_not_found);
}
};
final UserTimeline userTimeline = new UserTimeline.Builder().screenName(handleStr + "dfdfddfdfdfasdf") // Handle that doesn't exist
.includeReplies(false).includeRetweets(false).maxItemsPerRequest(5).build();
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(context)
.setTimeline(userTimeline)
.setViewStyle(R.style.tw__TweetLightWithActionsStyle)
.setOnActionCallback(actionCallback)
.build();
listView.setAdapter(adapter);
I think you misundestood the purpose of the actionCallback. From the source code of the TweetTimelineListAdapter you can see that this callback is for the actions on tweet view,ie, when you click on favorite icon for example. I've test with the favorite icon and the callback gets called.
Take a look at this comment at the getView method of the source code.
/**
* Returns a CompactTweetView by default. May be overridden to provide another view for the
* Tweet item. If Tweet actions are enabled, be sure to call setOnActionCallback(actionCallback)
* on each new subclass of BaseTweetView to ensure proper success and failure handling
* for Tweet actions (favorite, unfavorite).
*/
The callback is not intended to handle a screenname that does not exist and indeed the actions/buttons of a specific tweet.
Hope this helps.
UPDATED: You don't need to detect any erros on UserTimeLine, since the builder does not throw any exception and the adapter will be empty, with no rows/views showing on the screen. But if you still need to detect some "error" in the loading you have to rely on the "next" method of the UserTimeLine.
Take a look
userTimeline.next(null, new Callback<TimelineResult<Tweet>>() {
#Override
public void success(Result<TimelineResult<Tweet>> result) {
}
#Override
public void failure(TwitterException exception) {
Log.d("TAG",exception.getMessage());
}
});
This method shows the next tweet for the user, if the failure callback get called you will know for sure that this user does not have any tweet or the user does not exist.
I'm trying to implement in-app purchase in my latest android project.
To do so, I'm following this guide.
Everything went smooth until I used the dispose method in order to close any communication with the play store.
What I get is the following error:
Error:(101, 45) error: unreported exception IabAsyncInProgressException; must be caught or declared to be thrown
On the following code segment:
#Override
public void onDestroy() {
super.onDestroy();
//Always unbind the with the store connection, otherwise performance degradation of the device may follow.
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
After digging in the IabHelper class (Java) I found the dispose method.
Here the code of the method:
/**
* Dispose of object, releasing resources. It's very important to call this
* method when you are done with this object. It will release any resources
* used by it such as service connections. Naturally, once the object is
* disposed of, it can't be used again.
*/
public void dispose() throws IabAsyncInProgressException {
synchronized (mAsyncInProgressLock) {
if (mAsyncInProgress) {
throw new IabAsyncInProgressException("Can't dispose because an async operation " +
"(" + mAsyncOperation + ") is in progress.");
}
}
logDebug("Disposing.");
mSetupDone = false;
if (mServiceConn != null) {
logDebug("Unbinding from service.");
if (mContext != null) mContext.unbindService(mServiceConn);
}
mDisposed = true;
mContext = null;
mServiceConn = null;
mService = null;
mPurchaseListener = null;
}
What should I do to resolve this error?
I understand that I should catch and exception but I am not confident enough to change by myself this method in this class.
(Thanks for any help)
After more research I've found that this question was already asked and answered.
Unfortunately the question is still marked as not answered.
Here there is the link to the original question.
The solution is simple:
The file that you can get from the guide are outdated, and should be instead downloaded from github.
In the method onDestroy you should instead use the following code:
#Override
public void onDestroy() {
super.onDestroy();
//Always unbind the connection with the store, otherwise performance degradation of the device may follow.
if (mHelper != null) {
mHelper.disposeWhenFinished();
mHelper = null;
}
}
disposeWhenFinished it's a more elegant solution that works better than a dispose.
I have tried so many way but i can't succeed. I haven't found any source code examples for Android(about rekognition)
there's a source code in JAVA in the Developer Guide but i cannot implement that even though I tried TT
I try to detect faces by sending an image file from an external storage(from the emulator)
I don't know what i did wrong(I'm not good at coding)
Here is my code
AmazonRekognitionClient amazonRekognitionClient;
Image getAmazonRekognitionImage;
DetectFacesRequest detectFaceRequest;
DetectFacesResult detectFaceResult;
File file = new File(Environment.getExternalStorageDirectory(),"sungyeol.jpg.jpg");
public void test_00(View view) {
ByteBuffer imageBytes;
try{
InputStream inputStream = new FileInputStream(file.getAbsolutePath().toString());
imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
Log.e("InputStream: ",""+inputStream);
Log.e("imageBytes: ","");
getAmazonRekognitionImage.withBytes(imageBytes);
// Initialize the Amazon Cognito credentials provider
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-east-2:.......", // Identity Pool ID
Regions.US_EAST_2 // Region
);
//I want "ALL" attributes
amazonRekognitionClient = new AmazonRekognitionClient(credentialsProvider);
detectFaceRequest = new DetectFacesRequest()
.withAttributes(Attribute.ALL.toString())
.withImage(getAmazonRekognitionImage);
detectFaceResult = amazonRekognitionClient.detectFaces(detectFaceRequest);
detectFaceResult.getFaceDetails();
}
catch(Exception ex){
Log.e("Error on something:","Message:"+ex.getMessage());
}
and here is my errors
02-04 09:30:07.268 29405-29405/? E/InputStream:: java.io.FileInputStream#a9b23e7
02-04 09:30:07.271 29405-29405/? E/Error on something:: Message:Attempt to invoke virtual method 'com.amazonaws.services.rekognition.model.Image com.amazonaws.services.rekognition.model.Image.withBytes(java.nio.ByteBuffer)' on a null object reference
what is a null object reference?
i try to change the file path but he said no such file ... and when I change to this path, there's errors above.
by the way I've already asked a user for a permission to access a folder from Emulator in Android
please help me
PS. sorry for my bad English
Thank you in advance.
Now I am ok with the issues. I have been through many many things <3 <3 <3.
Thank you
I'm Thai and I had to try harder to find the solutions because there's lack of information in the particular language. Here are my solutions.
My solutions are:
0.There is an endpoint for setting for the Rekognition-->
http://docs.aws.amazon.com/general/latest/gr/rande.html#rekognition_region
1.On a "null object reference issue" I found that I have to create a new object first such as "Image image = new Image();" <-- The "new" command creates an object instance in that class
2.After the above error, there are more errors (Errors on NetworkOnMainThreadException), so I tried everything until I found this page -->
https://docs.aws.amazon.com/cognito/latest/developerguide/getting-credentials.html the page said that ...
Consequently, I looked up for more information about the AsyncTask and after that I created an AsyncTask class and then I move all my code about the initialize, the request, the response to the AsyncTask class. ตอนรันตอนท้ายๆน้ำตาจิไหล my code worked... TT and by the conclusion the sungyeol.jpg.jpg file worked
for example
private void testTask(){
.... all code in the main thread particularly on the requests and responses
from the services
//print the response or the result
//Log.e() makes the message in the android monitor red like an error
Log.e("Response:", [responseparameter.toString()]);
}
//create the inherited class from the AsyncTask Class
//(you can create within your activity class)
class AsyncTaskRunner extends AsyncTask<String,String,String>{
#Override
public String doInBackground(String ... input){
testTask(); // call the testTask() method that i have created
return null; // this override method must return String
}
}
//I've created a button for running the task
public void buttonTask(View view){
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
for more information about the AsyncTask:
https://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask
http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.WJdkqVOLTIU
I hope these help :)
I've been running into a problem using the AWS Mobile SDK version 2.2.15. After carefully looking at their own S3TransferUtilitySample, I have made a couple attempts to get a file uploaded to an Amazon S3 bucket on my own.
My first attempt was to try calling the TransferUtility's .upload() method from within Android's own AsyncTask, inside the doInBackground() method. No success there, and after reading about this issue, it inspired me to try moving the SDK calls outside of the AsyncTask and into the UI thread under onPostExecute() in suspicion that the call itself is asynchronous and the AsyncTask is running garbage collection on the AWS SDK objects. Still no luck, no exceptions are being thrown, and no indication of anything going wrong aside from the file not actually uploading.
My second attempt was following this exact example. I downloaded the source and was able to supply the application with the correct identity pool ID, region, bucket, key, and a test jpeg file. I ran the application and the calls were being made. The file made it to AWS S3 without any issues.
I copied their exact methods into a helper class of my application, and made all the AWS SDK objects a static field of the class, but I am still running into the same issue of no exceptions being thrown. I ended up making the fields non-static and instantiating the helper class as an object in my main activity, safely assuming that the object would not be treated with garbage collection. Still nothing! No indication of failure from these calls!
I decided to get really generous with logging using Android's Log.i() method, watching every step of the way, and it even makes it to the TransferUtility's .upload() method, but even having the TransferListener set and full of logging lines, there is no status change, onError() is not being called. TransferUtility's .upload() and its resulting TransferObserver object is not reporting anything like it was running the test application.
Here are a couple things to note:
* The correct identity pool ID is being used here, no issue with that
* I have tried using both version 2.2.15 as well as 2.2.13
* All dependencies included are .jar files, the project is not Gradle (yet)
* The service is declared in the manifest just as it was in the examples
* There are no build errors, Android Studio builds the project just fine
* The TransferListener object is not firing onStateChanged(), onProgressChanged(), nor onError()
Has anyone encountered such a strange issue with AWS S3 SDK? Any suggestions on how I can better debug this issue?
Here's the class right now:
public class AmazonS3Helper
{
Context context;
public String bucket;
public String key;
public File file;
public AmazonS3 s3;
public TransferUtility utility;
public AmazonS3Helper(JSONObject p, Context c)
{
Log.i("tag", "new AmazonS3Helper object");
this.context = c;
try
{
bucket = p.getString("bucket");
key = p.getString("key");
this.file = new File(
c.getExternalFilesDir(null),
"nn_temp_photo.jpg");
credentialsProvider();
setTransferUtility();
upload();
}
catch (Exception x)
{
Log.i("tag", "Error in new AmazonS3Helper object: " + x.getMessage());
}
}
public void credentialsProvider()
{
Log.i("tag", "Providing credentials");
try
{
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
this.context,
// This has been verified to return the correct identity pool
MyApplicationClass.getPreference("aws.credentials"),
Regions.US_EAST_1);
setAmazonS3Client(credentialsProvider);
}
catch (Exception x)
{
Log.i("tag", "Error in providing credentials: " + x.getMessage());
}
}
public void setAmazonS3Client(CognitoCachingCredentialsProvider credentialsProvider)
{
Log.i("tag", "Setting amazon s3 client");
try
{
s3 = new AmazonS3Client(credentialsProvider);
s3.setRegion(Region.getRegion(Regions.US_EAST_1));
}
catch (Exception x)
{
Log.i("tag", "Error in setting amazon s3 client:" + x.getMessage());
}
}
public void setTransferUtility()
{
Log.i("tag", "Setting transfer utility");
try
{
utility =
new TransferUtility(
s3,
this.context);
}
catch (Exception x)
{
Log.i("tag", "Error in setting transfer utility: " + x.getMessage());
}
}
public void upload()
{
Log.i("tag", "uploading");
try
{
TransferObserver transferObserver = utility.upload(
bucket,
key,
file
);
transferObserverListener(transferObserver);
}
catch (Exception x)
{
Log.i("tag", "Error in uploading: " + x.getMessage());
}
}
public void transferObserverListener(TransferObserver transferObserver)
{
Log.i("tag", "transferObserverListener");
try
{
transferObserver.setTransferListener(new TransferListener()
{
#Override
public void onStateChanged(int id, TransferState state)
{
Log.i("tag", state + "");
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal)
{
int percentage = (int) (bytesCurrent / bytesTotal * 100);
Log.i("tag", percentage + "");
}
#Override
public void onError(int id, Exception ex)
{
Log.i("tag", "error");
}
});
}
catch (Exception x)
{
Log.i("tag", "Error in transferObserverListener: " + x.getMessage());
}
}
}
Edit
I forgot to mention, but the version of Android this is being tested on is Android Lollipop 5.1.
This is a bug in 2.2.15. Some IO exceptions aren't reported. It is fixed in 2.2.16. Would you please try the latest version?
The issue has been solved and is entirely unrelated to the code itself. What was happening was that I was declaring the com.amazonaws.mobileconnectors.s3.transferutility.TransferService in the library's manifest, but the child apps also needed it in their manifest.
I found this out by dropping the sample Activity straight into my application, and realizing the child apps also needed this activity declaration. The child apps have no code themselves, but without the declaration in their own manifest, they are unaware the activities/services being referenced exist. In this case, Amazon was silently refusing to upload because the service wasn't declared for the specific application.
I'm trying to connect to .NET 4.0 webservice I created for receiving SOAP-calls from Android-devices, now hosted on local IIS for testing purposes.
I found out that ksoap2 would be an excellent class library for doing what i want to do. Downloaded the .jar package from https://code.google.com/p/ksoap2-android/ and started pounding the keyboard in ecstacy... with my fingers.
The amount of information being sent is from few kilobytes to few megabytes.
What is working
HttpTransportSE.call(String, SoapSerializationEnvelope)-method works perfectly while still in Eclipse's Android emulator, sending the call to webservice hosted in local IIS. Even tested that the webservice receives empty calls from trying to open the service address from a web browser in the same local area network.
What doesn't work
When I copy the .apk-file to an Android device, install it, start it and trying to make the call, the whole program freezes without making the call.
As you can see from a code block presented some lines after that possible errors are being taken into account: In emulated environment a successful call returns a SoapPrimitive-object or flows into the correct catch block generating an error message for the user according to the current situation.
Then on live Android device, program loses it's responsivity forever and has to be terminated from application menu.
What have i tried
I removed the call from the asynchronous method, and tried calling it straight from an anonymous inner function assigned for a button click-event.
Tried not trying to get a response, just making the call.
Tried getting a logcat-program for the device to see what's happening behind the UI, found two, they needed root access, which i don't have in the device. This is why i don't have any logcats to show you, and showing the emulator logcat would probably(?) be useless because it works fine there.
Not trying to connect to localhost.
Tried installing the program on older Lenovo-tablet running Android 4.2.2 and on brand new Samsung Galaxy Tab, both would have the same problem while otherwise working well.
The code
Here's the asynchronous method for making the call in device/emulator, where variables str_URL and soapRequest are a correct service address (checked) and a well formed SoapObject respectively:
#Override
protected WebServiceResult doInBackground(Void... v) {
WebServiceResult _ret;
SoapSerializationEnvelope soapEnvelope= new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet=true;
soapEnvelope.setAddAdornments(false);
soapEnvelope.setOutputSoapObject(soapRequest);
HttpTransportSE conn = new HttpTransportSE(str_URL);
conn.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
conn.debug = true;
try {
conn.call(str_ACTION, soapEnvelope);
SoapObject o = (SoapObject)soapEnvelope.getResponse();
_ret = new WebServiceResult(o, WebServiceResultEnum.ok);
} catch (NetworkOnMainThreadException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.keskeytys);
} catch (HttpResponseException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.httpVirhe);
} catch (XmlPullParserException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.vaara_muoto);
} catch (SocketTimeoutException e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.aikakatkaisu);
} catch (Exception e) {
_ret = new WebServiceResult(null, WebServiceResultEnum.keskeytys);
}
return _ret;
}
Thank you in advance!
Is it possible you are doing something like this:
YourAsyncTask task = new YourAsyncTask();
WebServiceResult result = task.doInBackground();
Because that would be wrong, completely wrong. If you call doInBackground() directly it will run in the same Thread and not in a new one. You need to start the AsyncTask with execute() like this:
YourAsyncTask task = new YourAsyncTask();
task.execute();
You need to implement the AsyncTask like this:
public class ExampleTask extends AsyncTask<Void, Void, WebServiceResult> {
public interface FinishedListener {
public void onFinished(WebServiceResult result);
}
private final FinishedListener finishedListener;
public ExampleTask(FinishedListener listener) {
this.finishedListener = listener;
}
#Override
protected WebServiceResult doInBackground(Void... params) {
WebServiceResult result = ...;
return result;
}
#Override
protected void onPostExecute(WebServiceResult result) {
super.onPostExecute(result);
if(this.finishedListener != null) {
this.finishedListener.onFinished(result);
}
}
}
And if you implemented it that way you can use it like this:
ExampleTask task = new ExampleTask(new ExampleTask.FinishedListener() {
#Override
public void onFinished(WebServiceResult result) {
// This will be called if the task has finished
}
});
task.execute();
It seems that I had declared the minimum SDK as 14 and target SDK as 17 in AndroidManifest.xml. I didn't use any fancy things in newer sdk's so i lowered the target SDK to the same level as minimum SDK, 14. I also had an Avast! Antivirus service running on the tablet which i removed.
This solved my problem. It could be that probably the Avast! antivirus-program wanted to block all communications from applications not downloaded from Play-store. I don't know if changing the target SDK had much effect really.
Well, I had the same question as you. When it goes to the method transport.call, it pauses, and for a while, it throws a timeout problem. At first, I thought maybe the network was poor, but the server logcat shows it is not the problem. The request was fine and the response was good. My business process is like below:
First, I get a list from the server through ksoap inner a child thread, then cycle the list, send a ksoap request based on every item of the list. It means it will send another list.size() request. When debugging in a real device the above problems occured. I solved it by starting a new child thread after getting the list and making all the list.size requests in the new child thread. So, ksoap use in android may cause thread block which leads to ioexception. So when you put it in a new thread, it escapes from the parent catch exception and works fine.