In my app, images are saving successfully to gallery after editing. but quality is not up to the mark on physical device. I got 0.5mp to 0.7mp highest. but same app I open in emulator and after saving image I got pretty good quality of images (about 1.5mp to 3mp). didn't find the exact reason of this. will be glad if you help to find out. attaching my image saving code below.
public void saveAsFile(#NonNull final String str, #NonNull final SaveSettings saveSettings, #NonNull final OnSaveListener onSaveListener) {
Log.d(TAG, "Image Path: " + str);
this.parentView.saveFilter((OnSaveBitmap) new OnSaveBitmap() {
#Override
public void onBitmapReady(Bitmap bitmap) {
new AsyncTask<String, String, Exception>() {
#Override
public void onPreExecute() {
super.onPreExecute();
PhotoEditor.this.clearHelperBox();
PhotoEditor.this.parentView.setDrawingCacheEnabled(false);
}
#SuppressLint({"MissingPermission"})
public Exception doInBackground(String... strArr) {
Bitmap bitmap;
try {
FileOutputStream fileOutputStream = new FileOutputStream(new File(str), false);
if (PhotoEditor.this.parentView != null) {
PhotoEditor.this.parentView.setDrawingCacheEnabled(true);
if (saveSettings.isTransparencyEnabled()) {
bitmap = BitmapUtil.removeTransparency(PhotoEditor.this.parentView.getDrawingCache());
} else {
bitmap = PhotoEditor.this.parentView.getDrawingCache();
}
bitmap.compress(Bitmap.CompressFormat.PNG, 100 , fileOutputStream);
}
Log.d(PhotoEditor.TAG, "Filed Saved Successfully");
return null;
} catch (Exception e) {
e.printStackTrace();
Log.d(PhotoEditor.TAG, "Failed to save File");
return e;
}
}
#Override
public void onPostExecute(Exception exc) {
super.onPostExecute(exc);
if (exc == null) {
if (saveSettings.isClearViewsEnabled()) {
PhotoEditor.this.clearAllViews();
}
onSaveListener.onSuccess(str);
return;
}
onSaveListener.onFailure(exc);
}
}.execute();
}
public void onFailure(Exception exc) {
onSaveListener.onFailure(exc);
}
});
}
I tried in many ways but couldn't find the solution.
Related
Required Behaviour: I use following code to save images, and want to show them up in gallery(as we get to see images from whatsapp).
boolean downloadImage(Bitmap image) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Download started..", Toast.LENGTH_SHORT).show();
}
});
ContentResolver resolver = getApplicationContext().getContentResolver();
Uri imageCollection;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
imageCollection = MediaStore.Images.Media
.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
} else {
imageCollection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
String imgName = "IMG_"+System.currentTimeMillis()+".jpg";
ContentValues imgDetails = new ContentValues();
imgDetails.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imgDetails.put(MediaStore.Images.Media.DISPLAY_NAME, imgName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
imgDetails.put(MediaStore.Images.Media.IS_PENDING, 1);
imgDetails.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/DownloaderApp");
}
Uri imgUri = resolver.insert(imageCollection, imgDetails);
try {
OutputStream outputStream = resolver.openOutputStream(imgUri);
boolean saveResult = image.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
outputStream.close();
imgDetails.clear();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
imgDetails.put(MediaStore.Images.Media.IS_PENDING, 0);
}
resolver.update(imageCollection, imgDetails, null, null);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
MainActivity.this,
(saveResult) ?"Image Path: "+imgUri.getPath() :"Failed to save image!",
Toast.LENGTH_SHORT).show();
}
});
outputStream.close();
return saveResult;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
Current Situation: I can see images getting saved in File Manager at exact location DCIM/DownloaderApp, but these pictures do not appear in gallery, i.e. they are not publically visibe through MediaStore API(what I feel).
Targetted Android: Android 10
I know, I can use android:requestLegacyExternalStorage="true" in manifest. But I want the app to be perfectly compatible with android 11 as well. So don't want to do this.
imageCollection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
change VOLUME_EXTERNAL_PRIMARY to VOLUME_EXTERNAL
and lastly in
contentResolver.update(imageCollection,contentValues,null,null)
make little modification
contentResolver.update(imageUri,contentValues,null,null)
Your case contentValues name will be imageDetails.
you can see your photos on the gallery.
its a class assignment and I need to finish it today.
So basically the captured image is saved but it won't show up in the imgVpic imageview camera open up and the image captured is saved correctly with the correct file name but it just won't show up in the thumbnail that I set up, I checked in the gallery and the picture is there but again .. the image won't show in this imgVpic image view (i kept repeating this cause I can't post this question without "more details" since my post is mostly code, pls help I'm a student and I hate my teacher)
here is the code that I used
public class CaptureImgActivity extends AppCompatActivity {
final int CAMERA_RESULT=0;
Uri imgUri=null;
Button btTakePic;
ImageView imgVPic;
private void CaptureImageUri(){
String dir= Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).getAbsolutePath();
File folder=new File(dir + File.separator+"test");
boolean success=true;
if (!folder.exists()){
try {
success=folder.mkdir();
Toast.makeText(this,"Folder Create Successfull", Toast.LENGTH_SHORT).show();
}catch (Exception e){
success = !success;
e.printStackTrace();
}
}
if (success){
dir=dir+ File.separator+"test";
}
Calendar calendar=Calendar.getInstance();
File file= new File(dir,"test"+(calendar.getTimeInMillis()+".jpg"));
if (!file.exists()){
try {
file.createNewFile();
imgUri= FileProvider.getUriForFile(CaptureImgActivity.this,BuildConfig.APPLICATION_ID,file);
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
startActivityForResult(intent,CAMERA_RESULT);
}catch (Exception e){
e.printStackTrace();
}
}else {
try {
file.delete();
file.createNewFile();
imgUri= FileProvider.getUriForFile(CaptureImgActivity.this,BuildConfig.APPLICATION_ID,file);
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
startActivityForResult(intent,CAMERA_RESULT);
}catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == CAMERA_RESULT && requestCode == RESULT_OK){
try {
Uri imgUri=data.getData();
Bitmap bitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(),imgUri);
imgVPic.setImageBitmap(bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture_img);
btTakePic = (Button) findViewById(R.id.btTakePic);
imgVPic = (ImageView) findViewById(R.id.imgVPic);
btTakePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CaptureImageUri();
}
});
}
}
I tried in both method like choose image from gallery and Capture Image by adding
android:requestLegacyExternalStorage="true"
My Code is Different from yours but work as the same process but this works for me
Uri imgUri=null;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
String selectedImagePath;
private void SelectImage() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
getActivity());
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent pictureActionIntent = null;
pictureActionIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(
pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
imgUri= FileProvider.getUriForFile(Objects.requireNonNull(getContext()), BuildConfig.APPLICATION_ID + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
bitmap = null;
selectedImagePath = null;
if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
if (!f.exists()) {
Toast.makeText(getContext(), "Error while capturing image", Toast.LENGTH_LONG).show();
return;
}
try {
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(f.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
mImageView.setImageBitmap(bitmap);
//storeImageTosdCard(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) {
if (data != null) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
selectedImagePath = c.getString(columnIndex);
c.close();
bitmap = BitmapFactory.decodeFile(selectedImagePath); // load
mImageView.setImageBitmap(bitmap);
} else {
Toast.makeText(getContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
And both method works for me and displayed thumbnail
Hei there,
I m trying to make an App with Android-Studio that can record sound using a Bluetooth-HS.
I know there are a lot of posts close to this, but i tried all the answers and it wont work for me.
My code gives me back a filled bytebuffer, however testing proves, its always the Phones Mic not the Headset-Mic.
If anyone could take a look at my code and point out why it wont use the BT-HS, that would be a huge help for me.
public class Inhalation extends AppCompatActivity {
AudioManager audioManager;
AudioRecord audioRecord=null;
Button mrecord;
Button mpause;
boolean isRecording=false;
private Thread recordingThread = null;
private int bufferSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inhalation);
mrecord= findViewById(R.id.Button_Record_ID);
mpause=findViewById(R.id.Button_Pause_ID);
audioManager =(AudioManager) this.getSystemService(this.AUDIO_SERVICE);
}
//is supposed to start recording using the BT MIC. Can only be called if BTSCO is connected
private void startRecording() {
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
audioRecord.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}
//picks up the recorded audiobuffer and writes it into a file
private void writeAudioDataToFile() {
String filename="record";
byte saudioBuffer[] = new byte[bufferSize];
FileOutputStream os = null;
// TODO (4) Audiorecord Filecreation
try {
os = openFileOutput(filename, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("headset_rec","false filepath");
}
while (isRecording) {
audioRecord.read(saudioBuffer, 0, bufferSize);
try {
os.write(saudioBuffer, 0, bufferSize);
// os.write(saudioBuffer);
Log.d("headset_rec","writing"+saudioBuffer[0]);
} catch (IOException e) {
e.printStackTrace();
Log.d("headset_rec","writefail");
}
}
try {
os.close();
} catch (IOException e) {
Log.d("headset_rec","close");
e.printStackTrace();
}
}
//stops the recording
private void stopRecording() {
// stops the recording activity
if (null != audioRecord) {
isRecording = false;
audioRecord.stop();
audioRecord.release();
audioRecord = null;
recordingThread = null;
}
}
public void Record_On_Click(View view){
mpause.setEnabled(true);
mrecord.setEnabled(false);
requestRecordAudioPermission();
startRecording();
}
//Button to pause
public void Record_Pause_Click(View view){
stopRecording();
// readFromFile();
mrecord.setEnabled(true);
mpause.setEnabled(false);
}
//if BluetoothSCO is connected enables recording
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
System.out.println("ANDROID Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
Log.d("SCOO","connected");
mrecord.setEnabled(true);
}
if(AudioManager.SCO_AUDIO_STATE_DISCONNECTED==state){
Log.d("SCOO","disconnected");
mrecord.setEnabled(false);
}
}
};
//connects to the bluetoothHeadset doing the following:
#Override
protected void onResume() {
// TODO (5) Bluetooth Mik
// Start Bluetooth SCO.
if(isRecording){
mpause.setEnabled(true);
mrecord.setEnabled(false);
}
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
super.onResume();
}
//Disconnects from the Bluetoothheadset doing the following
#Override
protected void onDestroy() {
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
unregisterReceiver(mBluetoothScoReceiver);
super.onDestroy();
}
private void requestRecordAudioPermission() {//gets the permission to record audio
//check API version, do nothing if API version < 23!
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion > android.os.Build.VERSION_CODES.LOLLIPOP){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
Log.d("Activity_Request", "Wastn granted!");
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
Log.d("Activity_Request", "request!");
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
Log.d("Activity_Request", "take!");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
}
}
}
}
I have my download manager, and it work perfect if I try to download a file. But I have a problem.
I have 4 CardView in my activity and I set it onClickListener, so when I click one CardView it will download the file.
Here is the code to call the download function
cardviewR1 = findViewById(R.id.card_viewR1);
cardviewR1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R1Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
and here is the download function
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
pDialogDL.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialogDL.setIndeterminate(false);
pDialogDL.setMax(100);
pDialogDL.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
pDialogDL.dismiss();
if (result != null)
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
The code work in my app, but the problem is, when I try to add second CardView which is like this
cardviewR2 = findViewById(R.id.card_viewR2);
cardviewR2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R2Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
Yes it will download the second file, but it will overwrite the first file. I think the problem is right here
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
Anyone can help me with this code?
I need your help, Thanks
Fixed it by create a new Download Class separately in different file with activity, so the AsyncTask will be call again and again
thanks
I have created a Mono for Android application which uses the Zebra printing API. I have managed to get the ZSDK_API.jar file referenced in both a Java Bindings Library and a Standard Mono for Android application as defined HERE
I have added the .jar file to the JBL project (Jars folder) and set it's build action to InputJar
I also added the jar to the Mono for Android application with the build action set to AndroidJavaLibrary.
DiscoveryHandler
public class DiscoveryHandler : IDiscoveryHandler
{
private Discovery _reference;
public DiscoveryHandler(Discovery reference)
{
_reference = reference;
}
public void DiscoveryError(string message)
{
new UIHelper(_reference).showErrorDialogOnGuiThread(message);
}
public void DiscoveryFinished()
{
_reference.RunOnUiThread(() =>
{
Toast.MakeText(_reference, " Discovered " + _reference.discoveredPrinters.Count + " devices", ToastLength.Short).Show();
_reference.SetProgressBarIndeterminateVisibility(false);
});
}
public void FoundPrinter(DiscoveredPrinter printer)
{
_reference.RunOnUiThread(() =>
{
DiscoveredPrinterBluetooth p = (DiscoveredPrinterBluetooth)printer;
_reference.discoveredPrinters.Add(p.Address + " (" + p.FriendlyName + ")");
_reference.mArrayAdapter.NotifyDataSetChanged();
});
}
public void Dispose()
{
}
public IntPtr Handle
{
get { return _reference.Handle; }
}
}
Discovery.cs
public class Discovery : ListActivity
{
public List<string> discoveredPrinters = null;
public ArrayAdapter<string> mArrayAdapter;
private static IDiscoveryHandler btDiscoveryHandler = null;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
RequestWindowFeature(WindowFeatures.IndeterminateProgress);
SetContentView(Resource.Layout.discovery_results);
SetProgressBarIndeterminateVisibility(true);
discoveredPrinters = new List<string>();
SetupListAdapter();
btDiscoveryHandler = new DiscoveryHandler(this);
try
{
new Thread(new ThreadStart(() =>
{
Looper.Prepare();
try
{
RunOnUiThread(() => Toast.MakeText(this, "Trying", ToastLength.Short).Show());
BluetoothDiscoverer.FindPrinters(this, btDiscoveryHandler);
RunOnUiThread(() => Toast.MakeText(this, "And...", ToastLength.Short).Show());
}
catch (ZebraPrinterConnectionException zex)
{
new UIHelper(this).showErrorDialogOnGuiThread(zex.Message);
}
catch (ThreadInterruptedException iex)
{
new UIHelper(this).showErrorDialogOnGuiThread(iex.Message);
}
catch (Exception ex)
{
new UIHelper(this).showErrorDialogOnGuiThread(ex.Message);
}
finally
{
RunOnUiThread(() => Toast.MakeText(this, "Quitting looper", ToastLength.Short).Show());
Looper.MyLooper().Quit();
RunOnUiThread(() => Toast.MakeText(this, "Finished", ToastLength.Short).Show());
}
})).Start();
}
catch (Exception ex)
{
new UIHelper(this).showErrorDialogOnGuiThread(ex.Message);
}
}
private void SetupListAdapter()
{
mArrayAdapter = new ArrayAdapter<string>(this, global::Android.Resource.Layout.SimpleListItem1, discoveredPrinters);
ListAdapter = mArrayAdapter;
}
}
I have made sure the manifest is requesting Bluetooth and Bluetooth_Admin as well as internet.
The application builds, but when run simply crashes, no exception and just says "The Application Has Stopped Unexpectedly"
All the classes are being detected and compiled, but I have no idea why it is bombing like this. Has anyone succeeded with a Mono for Android - Zebra integration?
Dammit - I am a chop! Just as I posted it I got to thinking - it probably has something to do with the fact that I was implementing IntPtr Handle as the parent's handle - I was right. Here is the first step of working code (FIRST STEP - if I have to answer my own questions!):
public class Discovery : ListActivity, IDiscoveryHandler
{
public List<string> discoveredPrinters = null;
public ArrayAdapter<string> mArrayAdapter;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
RequestWindowFeature(WindowFeatures.IndeterminateProgress);
SetContentView(Resource.Layout.discovery_results);
SetProgressBarIndeterminateVisibility(true);
discoveredPrinters = new List<string>();
SetupListAdapter();
try
{
new Thread(new ThreadStart(() =>
{
Looper.Prepare();
try
{
BluetoothDiscoverer.FindPrinters(this, this);
}
catch (ZebraPrinterConnectionException zex)
{
new UIHelper(this).showErrorDialogOnGuiThread(zex.Message);
}
catch (ThreadInterruptedException iex)
{
new UIHelper(this).showErrorDialogOnGuiThread(iex.Message);
}
catch (Exception ex)
{
new UIHelper(this).showErrorDialogOnGuiThread(ex.Message);
}
finally
{
RunOnUiThread(() => Toast.MakeText(this, "Quitting looper", ToastLength.Short).Show());
Looper.MyLooper().Quit();
RunOnUiThread(() => Toast.MakeText(this, "Finished", ToastLength.Short).Show());
}
})).Start();
}
catch (Exception ex)
{
new UIHelper(this).showErrorDialogOnGuiThread(ex.Message);
}
}
private void SetupListAdapter()
{
mArrayAdapter = new ArrayAdapter<string>(this, global::Android.Resource.Layout.SimpleListItem1, discoveredPrinters);
ListAdapter = mArrayAdapter;
}
public void DiscoveryError(string message)
{
new UIHelper(this).showErrorDialogOnGuiThread(message);
}
public void DiscoveryFinished()
{
RunOnUiThread(() =>
{
Toast.MakeText(this, " Discovered " + discoveredPrinters.Count + " devices", ToastLength.Short).Show();
SetProgressBarIndeterminateVisibility(false);
});
}
public void FoundPrinter(DiscoveredPrinter printer)
{
RunOnUiThread(() =>
{
DiscoveredPrinterBluetooth p = printer.JavaCast<DiscoveredPrinterBluetooth>();
discoveredPrinters.Add(p.Address + " (" + p.FriendlyName + ")");
mArrayAdapter.NotifyDataSetChanged();
});
}
}
}