У меня есть программа, в которой мне нужно распечатать много документов, иногда до 300 страниц. То, что я делаю, - это создание собственного документа и его печать с использованием адаптера. Но когда я вызываю фрагмент, намерение печати вызывается дважды, и одно перекрывает другое, и когда я нажимаю кнопку «Назад», когда другой снова появляется, а затем снова возвращается к фрагменту, если я нажимаю кнопку «Назад», он снова вызывает адаптер.
Я создаю документ в asyn c task
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void checkGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
isGranted = true;
// Toast.makeText(getActivity(), "Permission granted", Toast.LENGTH_SHORT).show();
// Code for above or equal 23 API Oriented Device
// Your Permission granted already .Do next code
} else {
isGranted = false;
requestPermission(); // Code for permission
}
} else {
isGranted = true;
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.multiple_barcode, container, false);
backBt = view.findViewById(R.id.back_arrow_barcode);
barcodeList = view.findViewById(R.id.barcode_recycler);
printBt = view.findViewById(R.id.print_barcode);
saveBt = view.findViewById(R.id.save_barcode);
dialog = new Dialog(getContext());
checkGranted();
if (getArguments() != null) {
auctionId = getArguments().getString("auctionid");
auctionIds = getArguments().getStringArrayList("auctionidd");
title = getArguments().getString("title");
weight = getArguments().getString("weight");
dimensions = getArguments().getString("dimension");
}
Log.e(TAG, "onCreateView: here" + auctionIds.size());
adapter = new BarcodeAdapter(bitmaps, auctionIds, getContext(), title, dimensions, weight);
barcodeList.setLayoutManager(new LinearLayoutManager(getContext()));
barcodeList.setAdapter(adapter);
getBarcodeImage();
if (isGranted) {
printBarcode(bitmaps);
//printMethodCall();
}
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener((v, keyCode, event) -> {
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().getSupportFragmentManager().popBackStackImmediate();
/*MultipleListingFragment fragment = new MultipleListingFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame
, fragment, "multiple").addToBackStack(null).commitAllowingStateLoss();*/
}
return false;
});
saveBt.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("auctionId", auctionId);
AddListingConfirm addListingConfirm = new AddListingConfirm();
addListingConfirm.setArguments(bundle);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame
, addListingConfirm, "multiple").commitAllowingStateLoss();
});
printBt.setOnClickListener(v -> {
if (isGranted) {
printBarcode(bitmaps);
} else {
checkGranted();
}
});
return view;
}
private void printMethodCall() {
Log.e(TAG, "onCreateView: " + document.getPageNumber());
Toast.makeText(getActivity(), "PDF success", Toast.LENGTH_SHORT).show();
PrintManager printManager = (PrintManager) getActivity()
.getSystemService(Context.PRINT_SERVICE);
try {
PrintDocumentAdapter printAdapter = new PdfDocumentAdapter(getContext(), Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "barcode" + ".pdf");
printManager.print("Document", printAdapter, new PrintAttributes.Builder().build());
} catch (Exception e) {
Log.e(TAG, "onCreateView: " + e.getLocalizedMessage());
}
}
public Boolean printBarcode(ArrayList<Bitmap> bitmaps) {
try {
ProjectUtility.getUtilityInstance().showGifPopup(getContext(), true, dialog, " ");
new DocumentCreation().execute();
} catch (Exception e) {
Log.e(TAG, "printBarcode: " + e.getLocalizedMessage());
}
return true;
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(getActivity(), "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((MainActivity) getActivity()).updateStatusBarColor("#a4ce6b");
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setVisibility(View.GONE);
}
private void getBarcodeImage() {
Bitmap bitmap = null;
bitmaps.clear();
try {
for (String auctionId : auctionIds) {
bitmap = encodeAsBitmap(auctionId, BarcodeFormat.CODE_128, 600, 300);
bitmaps.add(bitmap);
}
adapter.notifyDataSetChanged();
} catch (WriterException e) {
e.printStackTrace();
}
}
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
private class BarcodeAdapter extends RecyclerView.Adapter<BarcodeAdapter.ViewHolder> {
private ArrayList<Bitmap> bitmaps;
private ArrayList<String> auctionIds;
private Context context;
private String title;
private String dimension;
private String weight;
public BarcodeAdapter(ArrayList<Bitmap> bitmaps, ArrayList<String> auctionIds, Context context, String title, String dimensions, String weight) {
this.bitmaps = bitmaps;
this.auctionIds = auctionIds;
this.context = context;
this.title = title;
this.dimension = dimensions;
this.weight = weight;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(context).inflate(R.layout.barcode_image, viewGroup, false);
return new BarcodeAdapter.ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
viewHolder.barcodeImage.setImageBitmap(bitmaps.get(i));
viewHolder.auctionId.setText(auctionIds.get(i));
viewHolder.auctionTitle.setText(title);
if (!weight.isEmpty()) {
viewHolder.dimensions.setText(dimension);
}
}
@Override
public int getItemCount() {
return bitmaps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView auctionId, auctionTitle, dimensions;
public ImageView barcodeImage;
public ViewHolder(@NonNull View itemView) {
super(itemView);
auctionId = itemView.findViewById(R.id.auction_id);
barcodeImage = itemView.findViewById(R.id.barcode);
dimensions = itemView.findViewById(R.id.dimensions);
auctionTitle = itemView.findViewById(R.id.auction_title);
}
}
}
public class PdfDocumentAdapter extends PrintDocumentAdapter {
Context context = null;
String pathName = "";
public PdfDocumentAdapter(Context ctxt, String pathName) {
context = ctxt;
this.pathName = pathName;
}
@Override
public void onLayout(PrintAttributes printAttributes, PrintAttributes printAttributes1, CancellationSignal cancellationSignal, LayoutResultCallback layoutResultCallback, Bundle bundle) {
if (cancellationSignal.isCanceled()) {
layoutResultCallback.onLayoutCancelled();
} else {
PrintDocumentInfo.Builder builder =
new PrintDocumentInfo.Builder(" file name");
builder.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(PrintDocumentInfo.PAGE_COUNT_UNKNOWN)
.build();
layoutResultCallback.onLayoutFinished(builder.build(),
!printAttributes1.equals(printAttributes));
}
}
@Override
public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor parcelFileDescriptor, CancellationSignal cancellationSignal, WriteResultCallback writeResultCallback) {
InputStream in = null;
OutputStream out = null;
try {
File file = new File(pathName);
in = new FileInputStream(file);
out = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
byte[] buf = new byte[16384];
int size;
while ((size = in.read(buf)) >= 0
&& !cancellationSignal.isCanceled()) {
out.write(buf, 0, size);
}
if (cancellationSignal.isCanceled()) {
writeResultCallback.onWriteCancelled();
} else {
writeResultCallback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
}
} catch (Exception e) {
writeResultCallback.onWriteFailed(e.getMessage());
Log.e(TAG, "onWrite: " + e.getMessage());
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
Log.e(TAG, "onWrite: " + e.getLocalizedMessage());
}
}
}
}
private final class DocumentCreation extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... voids) {
document = new Document();
String fpath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "barcode" + ".pdf";
File file = new File(fpath);
try {
PdfWriter.getInstance(document,
new FileOutputStream(file.getAbsoluteFile()));
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
int i = 0;
document.open();
Log.e(TAG, "doInBackground: " + bitmaps.size());
for (Bitmap bitmap : bitmaps) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
document.setPageCount(i);
// document.setPageSize(myImg);
document.newPage();
document.add(myImg);
document.add(new Paragraph(auctionIds.get(i)));
document.add(new Paragraph(title));
if (!weight.isEmpty()) {
document.add(new Paragraph(dimensions));
}
//document.addKeywords(auctionIds.get(i));
// step 5
// document.close();
Log.d("Suceess", "Sucess");
Log.e(TAG, "printBarcode: " + document.getPageNumber());
} catch (IOException | DocumentException e) {
e.printStackTrace();
// ProjectUtility.getUtilityInstance().showGifPopup(getContext(), false, dialog, " ");
return false;
}
i++;
}
// ProjectUtility.getUtilityInstance().showGifPopup(getContext(), false, dialog, " ");
document.close();
return true;
}
@Override
protected void onPostExecute(Boolean s) {
super.onPostExecute(s);
ProjectUtility.getUtilityInstance().showGifPopup(getContext(), false, dialog, " ");
printMethodCall();
}
}.