I want to show Toast (or progress bar) when clicking on the button "btnSearchImg". If before upload image, button clicked say "first pick image from gallary" and if after upload image clicked say "waiting". the toast before uploading image work fine but after uploading didn't work fine! my entire Activity code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_by_image);
Toasty.Config.getInstance().setTextSize(15).apply();
mSharedPreferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditor.putString(PREF_SKIP,null);
if(mSharedPreferences.contains(PREF_SKIP)){
Log.i("payment", "true");
} else {
try {
}catch (Exception e){
Toast.makeText(getApplicationContext(), "ERORR", Toast.LENGTH_LONG).show();
}
}
context = getApplicationContext();
pbImgRetrvialProccess = (ProgressBar)findViewById(R.id.pbImgRetrvialProccess);
tvPermissionLoadImg = (TextView)findViewById(R.id.tvPermissionLoadImg);
tvPermissionLoadImg.setTypeface(Base.getIranSansFont());
TextView tvSearchImageToolBarText = (TextView) findViewById(R.id.tvSearchImageToolBarText);
tvSearchImageToolBarText.setTypeface(Base.getIranSansFont());
ivGalleryImgLoad = (ImageView) findViewById(R.id.ivGalleryImgLoad);
btnSearchImgLoad = (Button) findViewById(R.id.btnSearchImgLoad);
btnSearchImg = (Button) findViewById(R.id.btnSearchImg);
btnSearchImgLoad.setOnClickListener(this);
btnSearchImg.setOnClickListener(this);
}
public StringBuilder uniformQuantization( File filePath ){...}
private StringBuilder chHistogram( Mat newImage ){...}
private void CopyAssets(String filename){...}
private void copyFile(InputStream in, OutputStream out) throws IOException {...}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearchImgLoad:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);}
OpenGallery();
break;
case R.id.btnSearchImg:
Toasty.success(getBaseContext(), "Waiting...", Toast.LENGTH_LONG).show();
FindSimilarRequestedImage();
break;
}
}
private void OpenGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE && data != null) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PICK_IMAGE);
} else {
selectedImageUri = data.getData();
ivGalleryImgLoad.setImageURI(selectedImageUri);
tvPermissionLoadImg.setVisibility(View.INVISIBLE);
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private void dateiLesenStringBuilder() {
FEATURE_PATH = context.getCacheDir().getPath() + "/" + FEATURE_NAME;
try {
FileOutputStream out = new FileOutputStream(FEATURE_PATH);
InputStream in = context.getAssets().open("coins/"+FEATURE_NAME);
byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) > 0){
out.write(buffer, 0, ch);
}
out.flush();
out.close();
in.close();
}catch (Exception e){
System.out.println(e);
}
final File featureList = new File(FEATURE_PATH);
Runnable runner = new Runnable() {
BufferedReader in = null;
#Override
public void run() {
try {
String sCurrentLine;
int lines = 0;
BufferedReader newbw = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
while (newbw.readLine() != null)
lines++;
in = new BufferedReader(new FileReader(featureList.getAbsolutePath()));
ArrayList<Double> nDistVal = new ArrayList<Double>();
ArrayList<String> nImagePath = new ArrayList<String>();
int count = 0;
while ((sCurrentLine = in.readLine()) != null) {
String[] featX = sCurrentLine.split(";")[1].split(" ");
nImagePath.add(sCurrentLine.split(";")[0]);
nDistVal.add(Distance.distL2(featX, queryFeatureX.toString().split(" ")));
count++;
}
ArrayList<Double> nstore = new ArrayList<Double>(nDistVal); // may need to be new ArrayList(nfit)
double maxDistVal = Collections.max(nDistVal);
Collections.sort(nDistVal);
sortedNImagePath = new ArrayList<String>();
for (int n = 0; n < nDistVal.size(); n++) {
int index = nstore.indexOf(nDistVal.get(n));
sortedNImagePath.add(nImagePath.get(index));
sortedNImageDistanceValues.add(String.valueOf(nDistVal.get(n) / maxDistVal));
String filePath = sortedNImagePath.get(0);
String minDistanceImg = sortedNImageDistanceValues.get(n);
FileNameFromPath = filePath.substring(filePath.lastIndexOf("/") + 1);
System.out.println("Distance values -> " + FileNameFromPath.toString());
System.out.println("Distance values -> " + minDistanceImg.toString());
}
} catch (Exception ex) {
String x = ex.getMessage();
System.out.println("ERORR" + x);
}
if (in != null) try {
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
Intent imgSearchedCoinNameIntent = new Intent(SearchByImageActivity.this, ImageSearchedCoinActivity.class);
imgSearchedCoinNameIntent.putExtra("imgSearchedCoinName", FileNameFromPath);
startActivity(imgSearchedCoinNameIntent);
}
}
};
Thread t = new Thread(runner, "Code Executer");
t.start();
}
}
If I put the "Waiting..." Toast after the FindSimilarRequestedImage() the toast will show up, but I need the toast show immediately after clicking on the btnSearchImg.
NOTE: Also in the dateiLesenStringBuilder() I removed the thread t that this part of code runs in normal flow and serial, but nothing changes!
Instead of toast use logcat to see if they run sequentially or not, maybe toast takes time to run
I solved this problem by putting the part of code in delay like below:
private void FindSimilarRequestedImage() {
if (ivGalleryImgLoad.getDrawable() != null) {
pbImgRetrvialProccess.setVisibility(View.VISIBLE);
Toasty.success(getBaseContext(), "Waiting ...", Toast.LENGTH_LONG).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
File loadedImageFilePath = new File(getRealPathFromURI(selectedImageUri));
queryFeatureX = uniformQuantization(loadedImageFilePath);
dateiLesenStringBuilder();
}
}, 5000);
} else {
Toasty.error(getBaseContext(), "first pick image from gallary", Toast.LENGTH_LONG).show();
}
}
Now before destroying activity throw functions, I first show the toast, then run other functions!
Related
I am trying to intercept ANR (Application Not Responding) in android devices. I am implementing FileObserver on /data/anr/traces.txt file and capture the logs.
I am able to read this file in Samsung Galaxy J7(Android 6.0.1) but not on other devices ex: Nexus 4 (Android 5) and Moto G5 plus (Android 7).
I want FileObserver to read traces.txt on all devices. Any help will be appreciated.
Following is my code:
public class MainActivity extends AppCompatActivity {
private FileObserver fileObs;
private File anrFile = new File("/data/anr/traces.txt");
private File newFile;
int count=0;
long epochTimeCurrent=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT >= 23){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.INTERNET,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
100);
}
fileObs = new FileObserver("/data/anr") {
#Override
public void onEvent(int i, #Nullable String s) {
if(i == FileObserver.CLOSE_WRITE) {
if (anrFile.exists()) {
System.out.println("ANR file available");
//boolean read = anrFile.canRead();
if (count == 0) {
//Log.i("ANRTest", "Traces.text is available ? "+read);
epochTimeCurrent = System.currentTimeMillis();
Log.e("ANRTest", "System time in epoch : "+epochTimeCurrent);
readContent(anrFile);
} else if(count > 0) {
//Log.i("ANRTest", "Count increased : "+count);
}
}
else {
System.out.println("ANR file not available");
}
}
}
};
fileObs.startWatching();
//code to simulate ANR
final RelativeLayout cont = findViewById(R.id.container);
Button btn = findViewById(R.id.btn_anr);
final TextView textView = new TextView(this);
textView.setText("ANR");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("Devtest : Inside onclick");
while (true) {
cont.addView(textView);
cont.removeView(textView);
}
//throw new ArrayIndexOutOfBoundsException();
//throw new RuntimeException("This is a crash");
}
});
}
public void readContent(File file) {
BufferedReader br = null;
FileReader fileReader;
String strLine = "";
try {
fileReader = new FileReader(file);
int pid = android.os.Process.myPid();
br = new BufferedReader(fileReader);
while( (strLine = br.readLine()) != null){
semusi.logger.Log.info(strLine);
//semusi.logger.Log.info("Hello there !");
//System.out.println(strLine);
if(strLine.contains("pid "+pid) && count==0) {
System.out.println("File content is : "+strLine);
long logTime = calcSubstring(strLine);
//semusi.logger.Log.info(strLine);
System.out.println("Log print time : "+logTime);
//1512364990000 and 1512364990670
if(logTime > epochTimeCurrent) {
//semusi.logger.Log.info(strLine);
if(strLine.contains("-- end")) {
}
}
count++;
}
}
fileReader.close();
br.close();
} catch (FileNotFoundException e) {
System.err.println("Unable to find the file: fileName");
} catch (IOException e) {
System.err.println("Unable to read the file: fileName");
}
}
public long calcSubstring(String rawStr) {
if(rawStr.contains("at")){
int index = rawStr.indexOf("2017");
//System.out.println("Index of 2017 is : "+index);
String dateSubs = rawStr.substring(index,index+19);
//System.out.println("Time substring : "+dateSubs);
//2017-12-04 10:42:28
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date gmt = null;
try {
gmt = formatter.parse(dateSubs);
} catch (ParseException e) {
e.printStackTrace();
}
long millisecondsSinceEpoch0 = gmt.getTime();
String asString = formatter.format(gmt);
System.out.println("Date after formatting : "+asString);
return millisecondsSinceEpoch0;
}
return 0;
}
}
I want to build XMPP android client for local server connection, which will able to send text along with live video chat. So initially I am trying to make simple chat application. Using this application I am able to see all the available users but when I try to send a message it does not reach to the server or another client. Can anyone help me to figure out where it the problem?
Chat activity:
public class ChatActivity extends Activity {
private static final int REQUEST_CODE_FOR_GALLERY = 1;
private static final int REQUEST_CODE_FOR_FILEMANAGER = 2;
private static String LOG_TAG = "- Chat Activity -";
private Context context;
private ListView chatListView;
private Button attatchmentButton;
private Button sendButton;
private EditText chatMessageEditText;
private ArrayList<ChatEntry> chatEntries;
private ChatAdapter chatAdapter;
private String fJID, fNickName;
private String mJID, mNickName;
private byte[] fAvatarByte, mAvatarByte;
private Bitmap fAvatarBitmap, mAvatarBitmap;
private XMPPConnection xmppConnection;
private FileTransferManager receiveFileManager;
private FileTransferManager sendFileManager;
private FileTransferListener listener;
private File externalStorageDirectory;
private String fileSrc;
private Handler sHandler, rHandler;
private Thread sThread;
private File rfile;
private LinearLayout layoutReceivingFile;
private LinearLayout layoutSendinfFile;
private ProgressBar rProgressBar;
private ProgressBar sProgressBar;
private ChatManager chatManager;
private Chat chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_chat);
// Context
context = this;
// View matching
chatListView = (ListView) findViewById(R.id.chat_message_listview);
attatchmentButton = (Button) findViewById(R.id.chat_attatchment_button);
sendButton = (Button) findViewById(R.id.chat_send_button);
chatMessageEditText = (EditText) findViewById(R.id.chat_message_edit_text);
layoutReceivingFile = (LinearLayout) findViewById(R.id.chat_file_transfer_receive_layout);
layoutSendinfFile = (LinearLayout) findViewById(R.id.chat_file_transfer_send_layout);
rProgressBar = (ProgressBar) findViewById(R.id.chat_receive_file_progress_bar);
sProgressBar = (ProgressBar) findViewById(R.id.chat_send_file_progress_bar);
// Event for attachment button
attatchmentButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("File attachment");
builder.setMessage("Choose your file type.");
builder.setNegativeButton("Picture", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_FOR_GALLERY);
}
});
builder.setPositiveButton("File", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ChatActivity.this, FilePickerActivity.class);
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".png");
extensions.add(".jpg");
extensions.add(".gif");
extensions.add(".tif");
extensions.add(".bmp");
extensions.add(".doc");
extensions.add(".docx");
extensions.add(".ppt");
extensions.add(".pptx");
extensions.add(".xls");
extensions.add(".xlsx");
extensions.add(".pdf");
extensions.add(".zip");
extensions.add(".rar");
intent.putExtra(FilePickerActivity.EXTRA_ACCEPTED_FILE_EXTENSIONS, extensions);
startActivityForResult(intent, REQUEST_CODE_FOR_FILEMANAGER);
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
// Event for send message button
sendButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
String message = chatMessageEditText.getText().toString();
if ( message.trim().length() == 0 ) {
Toast.makeText(context, "Please fill up some text.", Toast.LENGTH_SHORT).show();
} else {
try {
chat.sendMessage(message);
chatMessageEditText.setText(null);
Log.d(LOG_TAG, "Trying to send message 1");
Toast.makeText(context, "trying to send" +message.toString(), Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(false);
chatEntry.setFilePath(null);
chatEntry.setSenderJID(mJID);
chatEntry.setReceiverJID(fJID);
chatEntry.setSenderAvatarBitmap(mAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage(message);
Log.d(LOG_TAG, "Trying to send message 2");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
Log.d(LOG_TAG, "Trying to send message 3");
} catch (XMPPException e) {
Log.e(LOG_TAG, "Unable to send message: "+e.getMessage());
}
}
}
});
// Event for chat list view
chatListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long which) {
if ( chatEntries.get(position).isAttachedFile() ) {
File file = new File(chatEntries.get(position).getFilePath());
if ( isImageFile(file) ) {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "image/*");
startActivity(intent);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.fromFile(file));
startActivity(intent);
}
}
}
});
// Extras
Bundle bundle = getIntent().getExtras();
if ( bundle == null ) {
ChatActivity.this.finish();
} else {
// Get active connection
xmppConnection = MainActivity.getXMPPConnection();
if ( xmppConnection == null ) {
ChatActivity.this.finish();
} else {
// For BEEM
FileTransferNegotiator.IBB_ONLY = true;
// -- END OF FOR BEEM
// Enable Server Discovery Manager
ServiceDiscoveryManager sdm = new ServiceDiscoveryManager(xmppConnection);
// sdm.addFeature("http://jabber.org/protocol/ibb");
// FOR BEEM
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("http://jabber.org/protocol/disco#item");
sdm.addFeature("jabber:iq:privacy");
// -- END OF FOR BEEM
// Receive data from extras
fJID = bundle.getString("fJID");
fJID += "/"+ApplicationSetting.SERVER_RESOURCE;
fNickName = bundle.getString("fNickName");
fAvatarByte = bundle.getByteArray("fAvatarByte");
fAvatarBitmap = BitmapUtility.convertByteArrayToBitmap(fAvatarByte);
mJID = bundle.getString("mJID");
mNickName = bundle.getString("mNickName");
mAvatarByte = bundle.getByteArray("mAvatarByte");
mAvatarBitmap = BitmapUtility.convertByteArrayToBitmap(mAvatarByte);
Toast.makeText(context, "fjid is "+fJID + "mjid is "+mJID, Toast.LENGTH_LONG).show();
// Initialize
chatMessageEditText.setSingleLine(true);
chatEntries = new ArrayList<ChatEntry>();
chatAdapter = new ChatAdapter(context, chatEntries, mJID);
chatListView.setAdapter(chatAdapter);
chatListView.setDivider(null);
fileSrc = null;
rProgressBar.setMax(100);
sProgressBar.setMax(100);
sProgressBar.setClickable(false);
rProgressBar.setClickable(false);
layoutReceivingFile.setVisibility(View.GONE);
layoutSendinfFile.setVisibility(View.GONE);
// Set title for this activity
setTitle("Chat with "+fNickName);
Log.i(LOG_TAG, mNickName+" chat with "+fNickName);
// Create Chat Manager
chatManager = xmppConnection.getChatManager();
// Add Chat Listener
chatManager.addChatListener(new ChatManagerListener() {
public void chatCreated(Chat chat, boolean isCreated) {
Toast.makeText(context, "Chat was created.", Toast.LENGTH_LONG).show();
Log.i(LOG_TAG, "Chat was created.");
}
});
// Create chat channel with friend
final Handler chatHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 1:
org.jivesoftware.smack.packet.Message chatMessage;
chatMessage = (org.jivesoftware.smack.packet.Message) msg.obj;
Toast.makeText(context, "Chat message." +msg.toString(), Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(false);
chatEntry.setFilePath(null);
chatEntry.setSenderJID(fJID);
chatEntry.setReceiverJID(mJID);
chatEntry.setSenderAvatarBitmap(fAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage(chatMessage.getBody());
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
}
}
};
chat = chatManager.createChat(fJID, new MessageListener() {
public void processMessage(Chat chat, final org.jivesoftware.smack.packet.Message chatMessage) {
Toast.makeText(context, "chatManager.createChat(fJID, new MessageListener() " , Toast.LENGTH_LONG).show();
if ( chatMessage.getBody() != null ) {
new Thread() {
public void run() {
Message msg = new Message();
msg.what = 1;
msg.obj = chatMessage;
Toast.makeText(context, "Chat message.before chathandler" +msg.toString(), Toast.LENGTH_LONG).show();
chatHandler.sendMessage(msg);
};
}.start();
Log.i(LOG_TAG, "Received message from: "+chatMessage.getFrom()+": "+chatMessage.getBody());
}
}
});
// Setup file transfer manager
receiveFileManager = new FileTransferManager(xmppConnection);
sendFileManager = new FileTransferManager(xmppConnection);
// Setup default saving directory ('mychat' on sd card)
externalStorageDirectory = new File(Environment.getExternalStorageDirectory(), "mychat");
// Setup handler for receive file listener
rHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 0:
// Finish with error
layoutReceivingFile.setVisibility(View.GONE);
Toast.makeText(context, "Unable to receive file.", Toast.LENGTH_LONG).show();
break;
case 1:
// Finish with complete
layoutReceivingFile.setVisibility(View.GONE);
Toast.makeText(context, "You have received new file.", Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(true);
chatEntry.setFilePath(rfile.getAbsolutePath());
chatEntry.setSenderJID(fJID);
chatEntry.setReceiverJID(mJID);
chatEntry.setSenderAvatarBitmap(fAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage("You just received an attachment.");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
case 2:
// Streaming
layoutReceivingFile.setVisibility(View.VISIBLE);
break;
}
}
};
// Setup receive file listener
listener = new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
Log.i(LOG_TAG, "Receive file coming");
new Thread() {
public void run() {
IncomingFileTransfer transfer = request.accept();
rfile = new File(externalStorageDirectory, transfer.getFileName());
try {
transfer.recieveFile(rfile);
Log.i(LOG_TAG, "Start receive file.");
while ( !transfer.isDone() ) {
try {
sleep(1000);
int percent = (int)(transfer.getProgress()*100);
if ( percent == 100 ) {
rProgressBar.setProgress(0);
} else {
rProgressBar.setProgress(percent);
}
Log.i(LOG_TAG, "Receiving file: "+percent+" %");
rHandler.sendEmptyMessage(2);
} catch ( InterruptedException e ) {
e.printStackTrace();
Log.e(LOG_TAG, "Receiving thread was interrupoted: "+e.getMessage());
}
}
if ( transfer.getStatus().equals(Status.complete) ) {
rHandler.sendEmptyMessage(1);
Log.i(LOG_TAG, "Receive file Completed.");
} else if ( transfer.getStatus().equals(Status.cancelled) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Cancelled.");
} else if ( transfer.getStatus().equals(Status.error) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Error.");
} else if ( transfer.getStatus().equals(Status.refused) ) {
rHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Receive file Refused.");
}
} catch ( Exception e ) {
Log.e(LOG_TAG, "Unable to receive file: "+e.getMessage());
}
};
}.start();
}
};
// Add receive file listener
receiveFileManager.addFileTransferListener(listener);
}
}
}
// Send file
public void sendFile(final File file) {
sHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch ( msg.what ) {
case 0:
// Finish with error
layoutSendinfFile.setVisibility(View.GONE);
Toast.makeText(context, "Unable to send file.", Toast.LENGTH_LONG).show();
break;
case 1:
// Finish with complete
layoutSendinfFile.setVisibility(View.GONE);
Toast.makeText(context, "Your file has been sent.", Toast.LENGTH_LONG).show();
ChatEntry chatEntry = new ChatEntry();
chatEntry.setAttachedFile(true);
chatEntry.setFilePath(fileSrc);
chatEntry.setSenderJID(mJID);
chatEntry.setReceiverJID(fJID);
chatEntry.setSenderAvatarBitmap(mAvatarBitmap);
chatEntry.setWhen(System.currentTimeMillis());
chatEntry.setMessage("Your attachment has been sent.");
chatEntries.add(chatEntry);
chatAdapter.setData(chatEntries);
chatAdapter.notifyDataSetChanged();
chatListView.setSelection(chatEntries.size()-1);
break;
case 2:
// Streaming
layoutSendinfFile.setVisibility(View.VISIBLE);
break;
}
}
};
sThread = new Thread() {
#Override
public void run() {
Log.i(LOG_TAG, "Send file coming");
OutgoingFileTransfer transfer = sendFileManager.createOutgoingFileTransfer(fJID);
try {
transfer.sendFile(file, "iChat-attachment-file");
Log.i(LOG_TAG, "Starting send file");
while ( !transfer.isDone() ) {
try {
sleep(1000);
int percent = (int)(transfer.getProgress()*100);
if ( percent == 100 ) {
sProgressBar.setProgress(0);
} else {
sProgressBar.setProgress(percent);
}
Log.i(LOG_TAG, "Sending file: "+percent+" %");
sHandler.sendEmptyMessage(2);
} catch (InterruptedException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Send file thread was interrupted: "+e.getMessage());
}
}
if ( transfer.getStatus().equals(Status.complete) ) {
sHandler.sendEmptyMessage(1);
Log.i(LOG_TAG, "Send file is completed");
} else {
sHandler.sendEmptyMessage(0);
Log.e(LOG_TAG, "Send file is failed");
}
} catch (XMPPException e) {
Log.e(LOG_TAG, "Unable to send file: "+e.getMessage());
}
}
};
sThread.start();
}
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
super.onActivityResult(requestCode, resultcode, intent);
if (requestCode == REQUEST_CODE_FOR_GALLERY) {
if (intent != null) {
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
fileSrc = cursor.getString(idx);
File file = new File(fileSrc);
if ( file.exists() ) {
sendFile(file);
} else {
Toast.makeText(context, "Image was not found, please try again.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == REQUEST_CODE_FOR_FILEMANAGER) {
if ( resultcode == RESULT_OK ) {
if( intent.hasExtra(FilePickerActivity.EXTRA_FILE_PATH) ) {
File file = new File(intent.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
// Set the file path text view
if ( file.exists() && isAllowedFileExtension(file) ) {
sendFile(file);
} else {
Toast.makeText(context, "This file is not allowed, please choose another file.", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
public boolean isAllowedFileExtension(File file) {
boolean result = false;
String filename = file.getName();
int length = filename.length();
int correctPosition = 0;
String ext = "";
for ( int i = length-1; i > 0; i-- ) {
if ( filename.charAt(i) == '.' ) {
correctPosition = i;
break;
}
}
if ( correctPosition == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
for ( int i = correctPosition+1; i < length; i++ ) {
ext += filename.charAt(i);
}
if ( ext.trim().length() == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
boolean isAllowedExtension = false;
String[] allowedExtension = new String[] { "png", "jpg", "gif", "tif", "bmp", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "pdf", "zip", "rar" };
for ( int i = 0; i < allowedExtension.length; i++ ) {
if ( ext.equalsIgnoreCase(allowedExtension[i]) ) {
isAllowedExtension = true;
}
}
if ( isAllowedExtension ) {
result = true;
}
}
}
return result;
}
public boolean isImageFile(File file) {
boolean result = false;
String filename = file.getName();
int length = filename.length();
int correctPosition = 0;
String ext = "";
for ( int i = length-1; i > 0; i-- ) {
if ( filename.charAt(i) == '.' ) {
correctPosition = i;
break;
}
}
if ( correctPosition == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
for ( int i = correctPosition+1; i < length; i++ ) {
ext += filename.charAt(i);
}
if ( ext.trim().length() == 0 ) {
Toast.makeText(context, "This file is invalid, please choose another file.", Toast.LENGTH_LONG).show();
} else {
boolean isAllowedExtension = false;
String[] allowedExtension = new String[] { "png", "jpg", "gif", "tif", "bmp" };
for ( int i = 0; i < allowedExtension.length; i++ ) {
if ( ext.equalsIgnoreCase(allowedExtension[i]) ) {
isAllowedExtension = true;
}
}
if ( isAllowedExtension ) {
result = true;
}
}
}
return result;
}
There is a memory leak reported by LeakCanary in my Android App. I have Googled and studied for days and cannot find any solution. The leaked object is an instance of Activity called "MakeFire". It seems to be related to android.view.WindowManagerGlobal. Can anyone point out how the leak happened, and how to fix it?
Here is the LeakCanary ScreenCap
Here is the source code of the MakeFire Activity
public class MakeFire extends SharedMethod implements StatusBarFragment.OnFragmentInteractionListener,
DayTimeFragment.OnFragmentInteractionListener, BackButtonFragment.OnFragmentInteractionListener {
private Button firePlough;
private Button bowDrill;
private TextView makeFireWithBowDrillTime;
private TextView requirementTextview;
private Button performButton;
private String selectedButton;
private boolean firePloughOn;
private boolean bowDrillOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_fire);
firePlough = (Button) findViewById(R.id.firePlough);
bowDrill = (Button) findViewById(R.id.bowDrill);
makeFireWithBowDrillTime = (TextView) findViewById(R.id.makeFireWithBowDrillTime);
requirementTextview = (TextView) findViewById(R.id.requirementTextview);
performButton = (Button) findViewById(R.id.performButton);
}
#Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
#Override
public void onBackPressed() {
Bundle extra = new Bundle();
extra.putString("classToGoBack", getClass().getName());
Intent intent = new Intent(this, InGameMenu.class);
intent.putExtras(extra);
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
GameData.useImmersiveModeSticky(this);
}
#Override
public void onStop() {
super.onStop();
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGame", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
//TODO - delete it before uploading the app
GameData.GDI.showPlainMsg("sharedMethodProblem!", this);
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
GameData.GDI.showPlainMsg(sw.getBuffer().toString(), this);
}
boolean savedGameIsFine;
try {
FileInputStream latestSavedGame = openFileInput("latestSavedGame");
ObjectInputStream latestGameData = new ObjectInputStream(latestSavedGame);
savedGameIsFine = (latestGameData.readObject() != null);
latestSavedGame.close();
} catch (Exception e) {
savedGameIsFine = false;
}
if (savedGameIsFine) {
try {
//save on the latest save file
FileOutputStream latestSavedGame = openFileOutput("latestSavedGameBackup", Context.MODE_PRIVATE);
ObjectOutputStream latestGameData = new ObjectOutputStream(latestSavedGame);
latestGameData.writeObject(GameData.GDI);
latestSavedGame.close();
} catch (Exception e) {
}
} else {
}
}
#Override
protected void onStart() {
super.onStart();
updateAllViews();
requirementTextview.setVisibility(View.INVISIBLE);
performButton.setVisibility(View.INVISIBLE);
}
//method for updating all amendable views in the page
private void updateAllViews() {
//visibility of fire plough button
if (GameData.GDI.anyThisInventoryAvailable(GameData.FIRE_PLOUGH) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
firePloughOn = true;
}
else {
firePlough.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_fireplow_3_f_o,0,0);
firePlough.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
firePloughOn = false;
}
//visibility of bow drill button
if (GameData.GDI.bowDrillUnlocked) {
bowDrill.setVisibility(View.VISIBLE);
makeFireWithBowDrillTime.setVisibility(View.VISIBLE);
if (GameData.GDI.anyThisInventoryAvailable(GameData.BOW_DRILL) &&
GameData.GDI.anyThisInventoryAvailable(GameData.TINDER) &&
(!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock)
) {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOnColour));
bowDrillOn = true;
}
else {
bowDrill.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.ic_bow_drill_3_f_o,0,0);
bowDrill.setTextColor(ContextCompat.getColor(this, R.color.buttonOffColour));
bowDrillOn = false;
}
}
updateStatusBarFragment();
updateDayTimeFragment();
}
public void makeFireWithFirePlough(View view) {
if (firePloughOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithFirePloughRqm);
selectedButton = "fire plough";
}
public void makeFireWithBowDrill(View view) {
if (bowDrillOn) {
performButton.setVisibility(View.VISIBLE);
}
else {
performButton.setVisibility(View.INVISIBLE);
}
requirementTextview.setVisibility(View.VISIBLE);
requirementTextview.setText(R.string.makeFireWithBowDrillRqm);
selectedButton = "bow drill";
}
public void perform(View view){
if (!GameData.GDI.stormOn || GameData.GDI.currentLocation.campfireWindBlock){
switch (selectedButton){
case "fire plough":
String msgToShow = "";
String extraInfo = "";
String[] timePassMsg;
Bundle extras = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg = GameData.GDI.timePass(30, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.firePloughDurability = GameData.GDI.updateInventoryDurability(GameData.FIRE_PLOUGH, GameData.GDI.firePloughDurability, GameData.FIRE_PLOUGH_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.firePloughDurability == GameData.FIRE_PLOUGH_MAX_DURABILITY) {
extraInfo += getString(R.string.firePloughBreakMsg) + "\n\n";
}
GameData.GDI.bowDrillUnlockCounter += 1;
if (Math.random() < 0.75) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow += getString(R.string.success) + "\n";
extras.putString("className", "Fire");
}
else {
msgToShow += getString(R.string.fail) + "\n";
if (!GameData.GDI.bowDrillUnlocked) {
if (GameData.GDI.bowDrillUnlockCounter >= 3) {
extraInfo += getString(R.string.bowDrillUnlockMsg) + "\n\n";
GameData.GDI.bowDrillUnlocked = true;
GameData.GDI.setCraftingAlertIcon(3);
}
}
extras.putString("className", "Make Fire");
}
Intent intent = new Intent(this, LoadingPage.class);
extras.putString("actionName", getString(R.string.makingFireWithFirePlough));
extras.putInt("timeNeeded", 30);
extras.putString("msgToShow", msgToShow);
extras.putString("extraInfo", extraInfo);
extras.putString("timePassMsg", timePassMsg[0]);
extras.putString("deathReason", timePassMsg[1]);
intent.putExtras(extras);
startActivity(intent);
break;
case "bow drill":
String msgToShow1 = "";
String extraInfo1 = "";
String[] timePassMsg1;
Bundle extras1 = new Bundle();
//timepass method must run before the fireToLast method
timePassMsg1 = GameData.GDI.timePass(10, 1, 1, 1, this);
if (GameData.GDI.anyThisInventoryInBackpack(GameData.TINDER)) {
GameData.GDI.setInventoryAmount(GameData.TINDER, true, -1);
}
else {
GameData.GDI.setInventoryAmount(GameData.TINDER, false, -1);
}
extras1.putString("toolUsed", getString(R.string.usedTinderMsg));
//update tool durability
GameData.GDI.bowDrillDurability = GameData.GDI.updateInventoryDurability(GameData.BOW_DRILL, GameData.GDI.bowDrillDurability, GameData.BOW_DRILL_MAX_DURABILITY);
//Because in GameCamp.updateInventoryDurability, if the tool broke, it will reset the durability to its maxDurability;
//so if these 2 numbers equal, the tool just broke
if (GameData.GDI.bowDrillDurability == GameData.BOW_DRILL_MAX_DURABILITY) {
extraInfo1 += getString(R.string.bowDrillBreakMsg) + "\n\n";
}
if (Math.random() < 0.95) {
GameData.GDI.currentLocation.fireOn = true;
GameData.GDI.currentLocation.fireToLast += 10;
msgToShow1 += getString(R.string.success) + "\n";
extras1.putString("className", "Fire");
}
else {
msgToShow1 += getString(R.string.fail) + "\n";
extras1.putString("className", "Make Fire");
}
Intent intent1 = new Intent(this, LoadingPage.class);
extras1.putString("actionName", getString(R.string.makingFireWithBowDrill));
extras1.putString("className", "Fire");
extras1.putInt("timeNeeded", 10);
extras1.putString("msgToShow", msgToShow1);
extras1.putString("extraInfo", extraInfo1);
extras1.putString("timePassMsg", timePassMsg1[0]);
extras1.putString("deathReason", timePassMsg1[1]);
intent1.putExtras(extras1);
startActivity(intent1);
break;
}
}
else {
GameData.GDI.showPlainMsg(getString(R.string.cannotMakeFireInStormMsg), this);
}
}
//fragment method
public void updateStatusBarFragment() {
StatusBarFragment statusBarFragment = (StatusBarFragment)getSupportFragmentManager().findFragmentById(R.id.statusBarFragment);
statusBarFragment.updateStatusBar();
}
public void updateDayTimeFragment() {
DayTimeFragment dayTimeFragment = (DayTimeFragment)getSupportFragmentManager().findFragmentById(R.id.dayTimeFragment);
dayTimeFragment.updateDayTimeView();
}
public void backButton(View view){
Intent intent = new Intent(this, Fire.class);
startActivity(intent);
}
}
I have some problem with printing image to AGPtEK 58mm Mini Bluetooth Pocket POS Thermal Receipt Printer. I am trying to convert webview content into image (this is working fine) and after that I want to print it with this printer but it prints only solid black background. Here is my code:
public class PrintDemo extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int PERMISSIONS_REQUEST_BLUETOOTH = 1;
private static final String TAG_REQUEST_PERMISSION = "Request permission";
private static final int PERMISSIONS_REQUEST_INTERNET = 0;
private static final int PERMISSIONS_REQUEST_BT_ADMIN = 2;
private static final int PERMISSIONS_REQUEST_LOCATION = 3;
private static final String WEB_SITE = "Remembered Web Site";
private static final String IS_CHECKED = "Check box";
#Bind(R.id.btn_search)
Button btnSearch;
#Bind(R.id.btn_print)
Button btnSendDraw;
#Bind(R.id.btn_open)
Button btnSend;
#Bind(R.id.btn_close)
Button btnClose;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("State", "Connecting...");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("State", "Not found");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
String path;
File dir;
File file;
#Bind(R.id.check_box)
CheckBox checkBox;
#Bind(R.id.txt_content)
EditText edtContext;
#Bind(R.id.web_view)
WebView webView;
BluetoothService mService;
BluetoothDevice con_dev;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.main);
ButterKnife.bind(this);
mService = new BluetoothService(this, mHandler);
if (!mService.isAvailable()) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.setWebViewClient(new WebViewClient() {
#SuppressLint("SdCardPath")
#Override
public void onPageFinished(final WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
siteToImage(view);
}
}, 5000);
}
});
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
checkPermissions();
}
private void siteToImage(WebView view) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setRememberedWeb() {
if (checkBox.isChecked()) {
String rememberedWeb = sharedPref.getString(WEB_SITE, "");
if (!rememberedWeb.equals("")) {
edtContext.setText(rememberedWeb);
}
}
}
#Override
protected void onPause() {
super.onPause();
saveState(checkBox.isChecked());
}
#Override
protected void onResume() {
super.onResume();
checkBox.setChecked(load());
setRememberedWeb();
}
private void saveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IS_CHECKED, isChecked);
if (isChecked) {
editor.putString(WEB_SITE, edtContext.getText().toString());
} else {
editor.putString(WEB_SITE, getString(R.string.txt_content));
}
editor.apply();
}
private boolean load() {
return sharedPref.getBoolean(IS_CHECKED, false);
}
private boolean checkPermissions() {
int permissionCheck =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
int permissionInternet =
ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permissionBTAdmin =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
int permissionLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bluetooth_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTPermission();
}
return false;
} else if (permissionInternet == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_internet_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestInternetPermission();
}
return false;
} else if (permissionBTAdmin == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bt_admin_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTAdminPermission();
}
return false;
} else if (permissionLocation == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_location_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestLocationPermission();
}
return false;
} else {
return true;
}
}
private void requestLocationPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
private void requestBTAdminPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},
PERMISSIONS_REQUEST_BT_ADMIN);
}
private void requestInternetPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.INTERNET},
PERMISSIONS_REQUEST_INTERNET);
}
private void requestBTPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
PERMISSIONS_REQUEST_BLUETOOTH);
}
#Override
public void onStart() {
super.onStart();
if (!mService.isBTopen()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_print);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btn_open);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("TAG", ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, file.getPath());
sendData = pg.printDraw();
mService.write(sendData);
}
public void downloadContent() {
if (!edtContext.getText().toString().equals("") && !edtContext.getText().toString().equals("https://")) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(edtContext.getText().toString())
.build();
HttpService service = retrofit.create(HttpService.class);
Call<ResponseBody> result = service.getContent();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
if (response.body() != null) {
String summary = response.body().string();
webView.loadData(summary, "text/html; charset=utf-8", null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
public interface HttpService {
#GET("/")
Call<ResponseBody> getContent();
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
downloadContent();
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
printImage();
}
}
}
}
The result is almost what I want you can see by yourself, but the printed image is not clear:
I fixed it guys, this was the problem, the method siteToImage(). Here are the changes I hope it will helps someone:
private void siteToImage() {
webView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint();
int iHeight = b.getHeight();
c.drawBitmap(b, 0, iHeight, paint);
webView.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
b.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.flush();
fos.close();
b.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
I'm creating a Fake Camera/Gallery app that just automatically return a random image. I tied it to the ACTION_PICK & IMAGE_CAPTURE intent filters.
However for the Gallery (PICK) code, after calling finish, it doesn't seem to be returning to the calling app.
Here's my code:
public class MainActivity extends Activity {
final static int[] photos = { R.drawable.android_1, R.drawable.android_2,
R.drawable.android_3 };
static int lastPhotoIndex = -1;
private final static String TAG = "FakeCameraGallery";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String action = getIntent().getAction();
if (action.contains("PICK")) {
//Act as Gallery
InputStream in = getResources().openRawResource(getNextPhoto());
Bitmap bm = BitmapFactory.decodeStream(in);
Bundle extras = new Bundle();
extras.putParcelable("data", bm);
Intent result = getIntent().putExtras(extras);
if (getParent() == null) {
setResult(Activity.RESULT_OK, result);
} else {
getParent().setResult(Activity.RESULT_OK, result);
}
} else {
//act as Camera
prepareToSnapPicture();
}
finish();
}
private void prepareToSnapPicture() {
checkSdCard();
Intent intent = getIntent();
if (intent.getExtras() != null) {
snapPicture(intent);
setResult(RESULT_OK);
} else {
Log.i(TAG, "Unable to capture photo. Missing Intent Extras.");
setResult(RESULT_CANCELED);
}
}
private void checkSdCard() {
if (!Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
Toast.makeText(this, "External SD card not mounted",
Toast.LENGTH_LONG).show();
Log.i(TAG, "External SD card not mounted");
}
}
private void snapPicture(Intent intent) {
try {
this.copyFile(getPicturePath(intent));
Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.i(TAG, "Can't copy photo");
e.printStackTrace();
}
}
private File getPicturePath(Intent intent) {
Uri uri = (Uri) intent.getExtras().get(MediaStore.EXTRA_OUTPUT);
return new File(uri.getPath());
}
private void copyFile(File destination) throws IOException {
InputStream in = getResources().openRawResource(getNextPhoto());
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
if (in != null) {
Log.i(TAG, "Input photo stream is null");
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
}
out.close();
}
private int getNextPhoto() {
if (lastPhotoIndex == photos.length - 1) {
lastPhotoIndex = -1;
}
return photos[++lastPhotoIndex];
}
}
Your code looks fine: are you calling it using startActivityForResult?