Hi i'd like to call this piece of android java code in unity with c# here the java code:
SmsDialog.getInstance().init(this);
//this is context of android activity
And right now i'm doing it like this in my c# code:
void ShowPaymentDialog()
{
AndroidJavaClass smsDialog = new AndroidJavaClass("com.mobagym.testsdkmobagym.SmsDialog");
smsDialog.CallStatic<AndroidJavaObject>("getInstance").Call("init",getContext());
}
AndroidJavaObject getContext()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
return jo;
}
There are no crashes or anything, Just that game stops and doesnt execute lines after ShowPaymentDialog.
void Start ()
{
ShowPaymentDialog();
GoogleAnalyticsV4.getInstance().LogScreen(MyMenuManager.SPLASH_SCREEN);
StartCoroutine(Next());
}
IEnumerator Next()
{
yield return new WaitForSeconds(duration);
SceneManager.LoadScene(MyMenuManager.MAIN_MENU);
}
so i'd like to know if i'm doing sth wrong with c# syntax. And if there are any ways to log this.
You should try to log the error as you mention.
Try setting up a try catch block.
Try {
//do some logic
} catch (Exception e){
//Log exception
}
Check this link:
https://docs.unity3d.com/ScriptReference/Debug.LogException.html
Maybe when you have stacktrace with exact error we can provide more assistance.
You are probably having a native java exception and missing it. You should connect a device to it and monitor the device log with adb logcat looking for your method call. This should give you enough information to continue debugging.
Related
I am new to android development so I think this may be a teething issue on my part, but I am currently trying to use the PixelCopy function in android studio. I have code as shown below, and it matches what the base class is expecting although it is returning an error. Would anyone be able to assist me with this issue?
The code I currently have is as follows:
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
SurfaceView current = new SurfaceView(view.getContext());
PixelCopy.OnPixelCopyFinishedListener copyResult;
// Make the request to copy.
PixelCopy.request(current, bitmap, copyResult, handlerThread);
if (copyResult. == PixelCopy.SUCCESS) {
//If successful do tasks in here
}
Try crating extracting finish listener as shown below in class.
private static void onPixelCopyFinished(int result) {
if (result != PixelCopy.SUCCESS) {
Log.e("err", "errMsg");
return;
}
}
You can pass the listener as below and also you'll also need to wrap it in try catch as it might throw an exception.
try {
PixelCopy.request(current, bitmap, <YOUR CLASS>::onPixelCopyFinished, this.getHandler());
} catch (IllegalArgumentException e) {
// PixelCopy may throw IllegalArgumentException, make sure to handle it
e.printStackTrace();
}
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'm trying to debug an app on my device and I'm having a bit of trouble with the debugger. I tried testing the logger to see if it would write to Logcat like so:
Log.d("MyActivity", "Testing logging...");
But nothing shows up in Logcat with the app: com.myapp.debug filter. It comes up when I simply filter by string (using my app name) but the entry looks like this:
01-08 13:45:07.468 29748-29748/? D/MyActivity﹕ Testing logging...
Does this question mark mean that something in the app is not getting passed through to the debugger? This might relate to my second issue with the debugger:
I've been debugging a crash and every time it happens, the phone simply shows the 'App is not responding' message then closes the current activity, disconnects the debugger, and the app keeps on running with the previous activity. No stack trace, no info about the crash, nothing. Is there something I need to set up in Android Studio to get this working?
I'm also having this trouble and I can't find too a good answer for this.
Instead I did a work around and catch the error with Thread.setDefaultUncaughtExceptionHandler() and Log it with Log.e()
I used this class to do it.
public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
private final String LINE_SEPARATOR = "\n";
public static final String LOG_TAG = ExceptionHandler.class.getSimpleName();
#SuppressWarnings("deprecation")
public void uncaughtException(Thread thread, Throwable exception) {
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
StringBuilder errorReport = new StringBuilder();
errorReport.append(stackTrace.toString());
Log.e(LOG_TAG, errorReport.toString());
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
Then in my Activity .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* catch unexpected error
*/
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
setContentView(R.layout.activity_main);
//other codes
}
Hope this helps.
I think it is the same adb or filer problem.
At first remove all filters.
Restart adb - type in terminal adb kill-server && adb start-server.
Probably your google analytics "ga_reportUncaughtExceptions" is set to true, turning it to false fixes the issue and exceptions get printed to logcat.Please refer to below link for further details.
Why does android logcat not show the stack trace for a runtime exception?
You should define a class that implement UncaughtExceptionHandler and use stackTraceToString in Kotlin:
import android.util.Log
import java.lang.Thread.UncaughtExceptionHandler
class ExceptionHandler : UncaughtExceptionHandler {
override fun uncaughtException(t: Thread, e: Throwable) {
val stackTrace: String = e.stackTraceToString()
Log.d("TAG", stackTrace)
}
}
and register it in your application:
Thread.setDefaultUncaughtExceptionHandler(ExceptionHandler())
Is it possible to change default sms application on Android 4.4 without user knowledge? I'm trying to do it on a ROOTED Galaxy S5 using reflection and invoking system methods, so here is what I done so far:
Created small app that implements all things needed for app to be a SMS manager (as per http://android-developers.blogspot.in/2013/10/getting-your-sms-apps-ready-for-kitkat.html) and I can make it default sms app but Android asks me to confirm that in dialog. Now I'm exploring android source code and I found something in this class:
https://github.com/android/platform_packages_apps_settings/blob/2abbacb7d46657e5863eb2ef0035521ffc41a0a8/src/com/android/settings/SmsDefaultDialog.java
So I'm trying to invoke internal method:
SmsApplication.setDefaultApplication(mNewSmsApplicationData.mPackageName, this);
via reflection and here is how I done it so far:
Class[] params = new Class[2];
params[0]=String.class;
params[1]=Context.class;
Class cls = null;
try {
cls = Class.forName("com.android.internal.telephony.SmsApplication");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method method = null;
try {
method = cls.getDeclaredMethod("getSmsApplicationData", params);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
Object[] params2 = new Object[2];
params2[0]=getPackageName();
params2[1]=getApplicationContext();
Log.d("Current package", getPackageName());
method.invoke(null, params2);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
And I made this app system app and put it into folder /system/priv-app, rebooted phone and started it successfully with adb, but when I click on the button that executes code above, nothing happens. No errors, no log output, but default app is still Messaging (com.android.mms).
Is there any way to do this?
This information contained in file /data/system/users/0/settings_secure.xml. For example, default application for SMS stored by key sms_default_application.
<setting id="85" name="sms_default_application" value="com.google.android.talk" package="com.android.settings" />
More info you can find in this class: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/provider/Settings.java#6067
Accordingly, if you have ROOT permissions, you can edit this file.
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.