PixelCopy android implementation - java

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();
}

Related

Error code (1, -2147483648) in Android MediaPlayer

I'm trying to implement a simple alarm in android by using the
MediaPlayer. However, every time I try to prepare() it, I get an error.
Here's my code. I'm a total beginner concerning Java and Android so
perhaps I'm doing something inherently wrong.
private void playDiscreteAlarm()
{
alarmSound = new MediaPlayer();
alarmSound.setAudioStreamType(AudioManager.STREAM_RING);
Resources res=context.getResources();
AssetFileDescriptor fd = res.openRawResourceFd(R.raw.discrete_alarm);
try {
alarmSound.setDataSource(fd.getFileDescriptor());
fd.close();
alarmSound.setLooping(true);
alarmSound.prepare();
alarmSound.start();
}
catch (IOException e)
{
Log.d("error\n");
}
}
The weird thing is that this worked once and after that stopped working.
It works when I use MediaPlayer.create() however I need to use the ringer volume instead of the media volume, and I believe this is the way to do it.
I fixed the problem, though I'm not sure what caused it. I just used a different and maybe slightly simpler method.
Here's what I did:
private void playDiscreteAlarm()
{
String filename = "android.resource://" + context.getPackageName() + "/raw/discrete_alarm";
alarmSound = new MediaPlayer();
alarmSound.setAudioStreamType(AudioManager.STREAM_RING);
try {
alarmSound.setDataSource(context, Uri.parse(filename));
alarmSound.setLooping(true);
alarmSound.prepare();
alarmSound.start();
}
catch (Exception e)
{
System.out.println(e);
}
}
Thanks !

Unity call android static function of java class

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.

How to get visible beacons from the RegionBootstrap AltBeacon method

I'm using the example code on this page (http://altbeacon.github.io/android-beacon-library/samples.html) in the Starting an App in the Background section and I've got a working app.
It detects whenever a beacon is in range even on background.
The problem is I need to know which beacon is it (UUID, Major, Minor) to then match it against my local database and throw a notification with the app still on background.
The didEnterRegion(Region region) function only has a matchesBeacon method, and I've tried doing the following to identify which of the beacons is being seen but it's throwing a NullPointerException:
public class SightSeeing extends Activity implements BootstrapNotifier, RangeNotifier {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Region region = new Region("sightRegion", null, null, null);
regionBootstrap = new RegionBootstrap(this, region);
BeaconManager.getInstanceForApplication(this).getBeaconParsers().add(
new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")
);
BeaconManager.getInstanceForApplication(this).setRangeNotifier(this);
}
#Override
public void didEnterRegion(Region region) {
regionBootstrap.disable();
BeaconManager.getInstanceForApplication(this).setRangeNotifier(this);
try {
BeaconManager.getInstanceForApplication(this).startRangingBeaconsInRegion(region);
}
catch (RemoteException e) {
Log.e(TAG, "Can't start ranging");
}
}
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
Iterator<Beacon> beaconIterator = beacons.iterator();
while (beaconIterator.hasNext()) {
Beacon beacon = beaconIterator.next();
//check if beacon exists in our DB and throw notification
}
}
}
Am I missing something obvious or isn't this possible with this library?
EDIT:
I've updated the code sample to give you guys a broader idea and I've tried implementing the suggestion by FOliveira without any success.
EDIT2:
Updated code to reflect the davidgyoung's suggestion. Still no luck. I have a Log.d() right on the first line of the didRangeBeaconsInRegion() function and it isn't being called.
I've tried adding BeaconManager.getInstanceForApplication(this).setRangeNotifier(this); before the try/catch block and the result is the same.
Did I implement the suggestion wrong or is there any other way to get this working?
If you want the app to launch itself on beacon detection, then the RegionBootstrap is the easiest way to go. In order to combine this with Ranging needed to detect individual beacons, then add code in your didEnterRegion method like this:
try {
BeaconManager.getInstanceForApplication(this).startRangingBeaconsInRegion(region);
}
catch (RemoteException e) {
Log.e(TAG, "Can't start ranging");
}
Then implement a ranging callback like you have.
You also need to remove the code below, which is probably what is causing your NullPointerException, because the :
for(int i=0; i< beaconsList.size(); i++) {
Beacon b = new Beacon.Builder()
.setId1(beaconsList.get(i).get("uuid"))
.setId2(beaconsList.get(i).get("major"))
.setId3(beaconsList.get(i).get("minor"))
.build();
if(region.matchesBeacon(b)) {
//get info from DB and throw notification
}
}
EDIT: I have updated the library's reference application to show how this can be done successfully. See here: https://github.com/AltBeacon/android-beacon-library-reference/blob/master/src/org/altbeacon/beaconreference/BeaconReferenceApplication.java
you can implement RangeNotifier interface and you can access all the beacon information captured in the public void didRangeBeaconsInRegion(Collection<Beacon> Beacons, Region region) method of that interface. Hope i got the question right

KSoap2 on Android freezing the device instead of making a webservice call

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.

Android: Wait for object to appear

I cannot think of a proper way to wait for an object to appear. I am writing a camera app. After taking a picture, I am writing GPS Data into the exif tags. I have to wait for the location object to appear, before writing. My quick and dirty fix is to start a new thread and use a while loop to "wait" for the object:
private static class MyRunnable implements Runnable {
private final String imagePath;
private final String thumbPath;
MyRunnable(final String anImagePath, String aThumbPath) {
this.imagePath = anImagePath;
this.thumbPath = aThumbPath;
}
public void run() {
while (mCurrentLocation == null) {
//do nothing
}
try {
writeExifTags(imagePath);
writeExifTags(thumbPath);
}
catch (NullPointerException e) {
Log.i(TAG, "NullPointerException");
}
}
}
This works but the empty while-loop looks very ugly. I think of some kind of handler for the object but cannot think of a way to use handlers to check for the existence of mCurrentLocation. Anyone with a flash of wit? :) (Yes the try/ catch block is obsolete now ^^)
You could try using an AsyncTask?

Categories

Resources