তথ্য বিনিময়

একবার ডিভাইসগুলির মধ্যে সংযোগ স্থাপন হয়ে গেলে, আপনি Payload অবজেক্টগুলি প্রেরণ এবং গ্রহণ করার মাধ্যমে ডেটা বিনিময় করতে পারেন৷ একটি Payload একটি সাধারণ বাইট অ্যারে উপস্থাপন করতে পারে, যেমন একটি ছোট পাঠ্য বার্তা; একটি ফাইল, যেমন একটি ছবি বা ভিডিও; অথবা একটি স্ট্রীম, যেমন ডিভাইসের মাইক্রোফোন থেকে অডিও স্ট্রিম।

sendPayload() পদ্ধতি ব্যবহার করে পাঠানো হয় এবং PayloadCallback এর বাস্তবায়নে প্রাপ্ত হয় যা সংযোগ পরিচালনা করুন -এ বর্ণিত acceptConnection() -এ পাস হয়।

পেলোডের প্রকারভেদ

বাইট

বাইট পেলোড হল সবচেয়ে সহজ ধরনের পেলোড। এগুলি সর্বাধিক Connections.MAX_BYTES_DATA_SIZE আকার পর্যন্ত বার্তা বা মেটাডেটার মতো সাধারণ ডেটা পাঠানোর জন্য উপযুক্ত৷ MAX_BYTES_DATA_SIZE৷ এখানে একটি BYTES পেলোড পাঠানোর একটি উদাহরণ:

Payload bytesPayload = Payload.fromBytes(new byte[] {0xa, 0xb, 0xc, 0xd});
Nearby.getConnectionsClient(context).sendPayload(toEndpointId, bytesPayload);

onPayloadReceived() পদ্ধতিটি প্রয়োগ করে একটি BYTES পেলোড গ্রহণ করুন যা আপনি PayloadCallback acceptConnection() এ পাস করেছেন।

static class ReceiveBytesPayloadListener extends PayloadCallback {

  @Override
  public void onPayloadReceived(String endpointId, Payload payload) {
    // This always gets the full data of the payload. Is null if it's not a BYTES payload.
    if (payload.getType() == Payload.Type.BYTES) {
      byte[] receivedBytes = payload.asBytes();
    }
  }

  @Override
  public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) {
    // Bytes payloads are sent as a single chunk, so you'll receive a SUCCESS update immediately
    // after the call to onPayloadReceived().
  }
}

FILE এবং স্ট্রিম পেলোডের বিপরীতে, BYTES STREAM একক অংশ হিসাবে পাঠানো হয়, তাই সফল আপডেটের জন্য অপেক্ষা করার দরকার নেই (যদিও এটি এখনও বিতরণ করা হবে, SUCCESS onPayloadReceived() এ কল করার পরপরই)। পরিবর্তে, onPayloadReceived() কল করার সাথে সাথে পেলোডের সম্পূর্ণ ডেটা পেতে আপনি নিরাপদে payload.asBytes() onPayloadReceived() কল করতে পারেন।

ফাইল

ফাইল পেলোডগুলি স্থানীয় ডিভাইসে সঞ্চিত একটি ফাইল থেকে তৈরি করা হয়, যেমন একটি ফটো বা ভিডিও ফাইল। এখানে একটি FILE পেলোড পাঠানোর একটি সহজ উদাহরণ:

File fileToSend = new File(context.getFilesDir(), "hello.txt");
try {
  Payload filePayload = Payload.fromFile(fileToSend);
  Nearby.getConnectionsClient(context).sendPayload(toEndpointId, filePayload);
} catch (FileNotFoundException e) {
  Log.e("MyApp", "File not found", e);
}

FILES পেলোড তৈরি করতে একটি ParcelFileDescriptor ব্যবহার করা আরও দক্ষ হতে পারে যদি একটি উপলব্ধ থাকে, উদাহরণস্বরূপ একটি ContentResolver থেকে। এটি ফাইলের বাইটের অনুলিপি কমিয়ে দেয়:

ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "r");
filePayload = Payload.fromFile(pfd);

যখন একটি ফাইল প্রাপ্ত হয়, তখন এটি প্রাপকের ডিভাইসে ডাউনলোড ফোল্ডারে ( DIRECTORY_DOWNLOADS ) একটি জেনেরিক নাম এবং কোনো এক্সটেনশন ছাড়াই সংরক্ষিত হয়৷ একবার স্থানান্তর সম্পূর্ণ হয়ে গেলে, PayloadTransferUpdate.Status.SUCCESS-এর সাথে PayloadTransferUpdate.Status.SUCCESS onPayloadTransferUpdate() এ একটি কল দ্বারা নির্দেশিত হলে, আপনি File অবজেক্টটি পুনরুদ্ধার করতে পারেন যদি আপনার অ্যাপ < Q ডিভাইসগুলিকে লক্ষ্য করে থাকে:

File payloadFile = filePayload.asFile().asJavaFile();

// Rename the file.
payloadFile.renameTo(new File(payloadFile.getParentFile(), filename));

যদি আপনার অ্যাপটি Q ডিভাইসগুলিকে লক্ষ্য করে, তাহলে আপনি পূর্ববর্তী কোড ব্যবহার চালিয়ে যেতে আপনার ম্যানিফেস্টের অ্যাপ্লিকেশন উপাদানে android:requestLegacyExternalStorage="true" যোগ করতে পারেন। অন্যথায়, Q+ এর জন্য আপনাকে Scoped Storage নিয়ম মেনে চলতে হবে এবং পরিষেবা থেকে পাস করা uri ব্যবহার করে প্রাপ্ত ফাইল অ্যাক্সেস করতে হবে।

// Because of https://developer.android.com/preview/privacy/scoped-storage, we are not
// allowed to access filepaths from another process directly. Instead, we must open the
// uri using our ContentResolver.
Uri uri = filePayload.asFile().asUri();
try {
  // Copy the file to a new location.
  InputStream in = context.getContentResolver().openInputStream(uri);
  copyStream(in, new FileOutputStream(new File(context.getCacheDir(), filename)));
} catch (IOException e) {
  // Log the error.
} finally {
  // Delete the original file.
  context.getContentResolver().delete(uri, null, null);
}

নিম্নলিখিত আরও জটিল উদাহরণে, ACTION_OPEN_DOCUMENT উদ্দেশ্য ব্যবহারকারীকে একটি ফাইল বেছে নিতে অনুরোধ করে এবং ফাইলটি দক্ষতার সাথে ParcelFileDescriptor ব্যবহার করে একটি পেলোড হিসাবে পাঠানো হয়। ফাইলের নামটি একটি BYTES পেলোড হিসাবেও পাঠানো হয়।

private static final int READ_REQUEST_CODE = 42;
private static final String ENDPOINT_ID_EXTRA = "com.foo.myapp.EndpointId";

/**
 * Fires an intent to spin up the file chooser UI and select an image for sending to endpointId.
 */
private void showImageChooser(String endpointId) {
  Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
  intent.addCategory(Intent.CATEGORY_OPENABLE);
  intent.setType("image/*");
  intent.putExtra(ENDPOINT_ID_EXTRA, endpointId);
  startActivityForResult(intent, READ_REQUEST_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
  super.onActivityResult(requestCode, resultCode, resultData);
  if (requestCode == READ_REQUEST_CODE
      && resultCode == Activity.RESULT_OK
      && resultData != null) {
    String endpointId = resultData.getStringExtra(ENDPOINT_ID_EXTRA);

    // The URI of the file selected by the user.
    Uri uri = resultData.getData();

    Payload filePayload;
    try {
      // Open the ParcelFileDescriptor for this URI with read access.
      ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "r");
      filePayload = Payload.fromFile(pfd);
    } catch (FileNotFoundException e) {
      Log.e("MyApp", "File not found", e);
      return;
    }

    // Construct a simple message mapping the ID of the file payload to the desired filename.
    String filenameMessage = filePayload.getId() + ":" + uri.getLastPathSegment();

    // Send the filename message as a bytes payload.
    Payload filenameBytesPayload =
        Payload.fromBytes(filenameMessage.getBytes(StandardCharsets.UTF_8));
    Nearby.getConnectionsClient(context).sendPayload(endpointId, filenameBytesPayload);

    // Finally, send the file payload.
    Nearby.getConnectionsClient(context).sendPayload(endpointId, filePayload);
  }
}

যেহেতু ফাইলের নামটি একটি পেলোড হিসাবে পাঠানো হয়েছিল, আমাদের রিসিভার ফাইলটিকে সরাতে বা পুনঃনামকরণ করতে পারে যাতে এটির একটি উপযুক্ত এক্সটেনশন থাকে:

static class ReceiveFilePayloadCallback extends PayloadCallback {
  private final Context context;
  private final SimpleArrayMap<Long, Payload> incomingFilePayloads = new SimpleArrayMap<>();
  private final SimpleArrayMap<Long, Payload> completedFilePayloads = new SimpleArrayMap<>();
  private final SimpleArrayMap<Long, String> filePayloadFilenames = new SimpleArrayMap<>();

  public ReceiveFilePayloadCallback(Context context) {
    this.context = context;
  }

  @Override
  public void onPayloadReceived(String endpointId, Payload payload) {
    if (payload.getType() == Payload.Type.BYTES) {
      String payloadFilenameMessage = new String(payload.asBytes(), StandardCharsets.UTF_8);
      long payloadId = addPayloadFilename(payloadFilenameMessage);
      processFilePayload(payloadId);
    } else if (payload.getType() == Payload.Type.FILE) {
      // Add this to our tracking map, so that we can retrieve the payload later.
      incomingFilePayloads.put(payload.getId(), payload);
    }
  }

  /**
   * Extracts the payloadId and filename from the message and stores it in the
   * filePayloadFilenames map. The format is payloadId:filename.
   */
  private long addPayloadFilename(String payloadFilenameMessage) {
    String[] parts = payloadFilenameMessage.split(":");
    long payloadId = Long.parseLong(parts[0]);
    String filename = parts[1];
    filePayloadFilenames.put(payloadId, filename);
    return payloadId;
  }

  private void processFilePayload(long payloadId) {
    // BYTES and FILE could be received in any order, so we call when either the BYTES or the FILE
    // payload is completely received. The file payload is considered complete only when both have
    // been received.
    Payload filePayload = completedFilePayloads.get(payloadId);
    String filename = filePayloadFilenames.get(payloadId);
    if (filePayload != null && filename != null) {
      completedFilePayloads.remove(payloadId);
      filePayloadFilenames.remove(payloadId);

      // Get the received file (which will be in the Downloads folder)
      // Because of https://developer.android.com/preview/privacy/scoped-storage, we are not
      // allowed to access filepaths from another process directly. Instead, we must open the
      // uri using our ContentResolver.
      Uri uri = filePayload.asFile().asUri();
      try {
        // Copy the file to a new location.
        InputStream in = context.getContentResolver().openInputStream(uri);
        copyStream(in, new FileOutputStream(new File(context.getCacheDir(), filename)));
      } catch (IOException e) {
        // Log the error.
      } finally {
        // Delete the original file.
        context.getContentResolver().delete(uri, null, null);
      }
    }
  }

  // add removed tag back to fix b/183037922
  private void processFilePayload2(long payloadId) {
    // BYTES and FILE could be received in any order, so we call when either the BYTES or the FILE
    // payload is completely received. The file payload is considered complete only when both have
    // been received.
    Payload filePayload = completedFilePayloads.get(payloadId);
    String filename = filePayloadFilenames.get(payloadId);
    if (filePayload != null && filename != null) {
      completedFilePayloads.remove(payloadId);
      filePayloadFilenames.remove(payloadId);

      // Get the received file (which will be in the Downloads folder)
      if (VERSION.SDK_INT >= VERSION_CODES.Q) {
        // Because of https://developer.android.com/preview/privacy/scoped-storage, we are not
        // allowed to access filepaths from another process directly. Instead, we must open the
        // uri using our ContentResolver.
        Uri uri = filePayload.asFile().asUri();
        try {
          // Copy the file to a new location.
          InputStream in = context.getContentResolver().openInputStream(uri);
          copyStream(in, new FileOutputStream(new File(context.getCacheDir(), filename)));
        } catch (IOException e) {
          // Log the error.
        } finally {
          // Delete the original file.
          context.getContentResolver().delete(uri, null, null);
        }
      } else {
        File payloadFile = filePayload.asFile().asJavaFile();

        // Rename the file.
        payloadFile.renameTo(new File(payloadFile.getParentFile(), filename));
      }
    }
  }

  @Override
  public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) {
    if (update.getStatus() == PayloadTransferUpdate.Status.SUCCESS) {
      long payloadId = update.getPayloadId();
      Payload payload = incomingFilePayloads.remove(payloadId);
      completedFilePayloads.put(payloadId, payload);
      if (payload.getType() == Payload.Type.FILE) {
        processFilePayload(payloadId);
      }
    }
  }

  /** Copies a stream from one location to another. */
  private static void copyStream(InputStream in, OutputStream out) throws IOException {
    try {
      byte[] buffer = new byte[1024];
      int read;
      while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
      }
      out.flush();
    } finally {
      in.close();
      out.close();
    }
  }
}

প্রবাহ

স্ট্রীম পেলোডগুলি উপযুক্ত যখন আপনি ফ্লাইতে তৈরি হওয়া প্রচুর পরিমাণে ডেটা পাঠাতে চান, যেমন একটি অডিও স্ট্রিম৷ Payload.fromStream() কল করে একটি STREAM পেলোড তৈরি করুন, একটি ইনপুটস্ট্রিম বা একটি InputStream এ পাস ParcelFileDescriptor ৷ উদাহরণ স্বরূপ:

URL url = new URL("https://developers.google.com/nearby/connections/android/exchange-data");
Payload streamPayload = Payload.fromStream(url.openStream());
Nearby.getConnectionsClient(context).sendPayload(toEndpointId, streamPayload);

প্রাপক, একটি সফল onPayloadTransferUpdate কলব্যাকে payload.asStream().asInputStream() অথবা payload.asStream().asParcelFileDescriptor() কল করুন:

static class ReceiveStreamPayloadCallback extends PayloadCallback {
  private final SimpleArrayMap<Long, Thread> backgroundThreads = new SimpleArrayMap<>();

  private static final long READ_STREAM_IN_BG_TIMEOUT = 5000;

  @Override
  public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) {
    if (backgroundThreads.containsKey(update.getPayloadId())
        && update.getStatus() != PayloadTransferUpdate.Status.IN_PROGRESS) {
      backgroundThreads.get(update.getPayloadId()).interrupt();
    }
  }

  @Override
  public void onPayloadReceived(String endpointId, Payload payload) {
    if (payload.getType() == Payload.Type.STREAM) {
      // Read the available bytes in a while loop to free the stream pipe in time. Otherwise, the
      // bytes will block the pipe and slow down the throughput.
      Thread backgroundThread =
          new Thread() {
            @Override
            public void run() {
              InputStream inputStream = payload.asStream().asInputStream();
              long lastRead = SystemClock.elapsedRealtime();
              while (!Thread.interrupted()) {
                if ((SystemClock.elapsedRealtime() - lastRead) >= READ_STREAM_IN_BG_TIMEOUT) {
                  Log.e("MyApp", "Read data from stream but timed out.");
                  break;
                }

                try {
                  int availableBytes = inputStream.available();
                  if (availableBytes > 0) {
                    byte[] bytes = new byte[availableBytes];
                    if (inputStream.read(bytes) == availableBytes) {
                      lastRead = SystemClock.elapsedRealtime();
                      // Do something with is here...
                    }
                  } else {
                    // Sleep or just continue.
                  }
                } catch (IOException e) {
                  Log.e("MyApp", "Failed to read bytes from InputStream.", e);
                  break;
                } // try-catch
              } // while
            }
          };
      backgroundThread.start();
      backgroundThreads.put(payload.getId(), backgroundThread);
    }
  }
}

একাধিক পেলোড সহ অর্ডার করা হচ্ছে

একই ধরণের পেলোডগুলি যে ক্রমে পাঠানো হয়েছিল সে অনুযায়ী পৌঁছানোর গ্যারান্টি দেওয়া হয়, তবে বিভিন্ন ধরণের পেলোডগুলির মধ্যে অর্ডার সংরক্ষণের কোনও গ্যারান্টি নেই৷ উদাহরণস্বরূপ, যদি একজন প্রেরক একটি BYTE পেলোডের পরে একটি FILE পেলোড পাঠায়, তাহলে প্রাপক প্রথমে BYTE পেলোড পেতে পারে, তারপরে FILE পেলোড।

অগ্রগতি আপডেট

onPayloadTransferUpdate() পদ্ধতি ইনকামিং এবং আউটগোয়িং উভয় পেলোডের অগ্রগতি সম্পর্কে আপডেট প্রদান করে। উভয় ক্ষেত্রেই, এটি ব্যবহারকারীর কাছে স্থানান্তরের অগ্রগতি প্রদর্শন করার একটি সুযোগ, যেমন একটি অগ্রগতি দণ্ড সহ। ইনকামিং পেলোডের জন্য, আপডেটগুলিও নির্দেশ করে যে কখন নতুন ডেটা গৃহীত হয়েছে।

নিম্নলিখিত নমুনা কোডটি বিজ্ঞপ্তির মাধ্যমে ইনকামিং এবং আউটগোয়িং পেলোডগুলির অগ্রগতি প্রদর্শন করার একটি উপায় প্রদর্শন করে:

class ReceiveWithProgressCallback extends PayloadCallback {
  private final SimpleArrayMap<Long, NotificationCompat.Builder> incomingPayloads =
      new SimpleArrayMap<>();
  private final SimpleArrayMap<Long, NotificationCompat.Builder> outgoingPayloads =
      new SimpleArrayMap<>();

  NotificationManager notificationManager =
      (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

  private void sendPayload(String endpointId, Payload payload) {
    if (payload.getType() == Payload.Type.BYTES) {
      // No need to track progress for bytes.
      return;
    }

    // Build and start showing the notification.
    NotificationCompat.Builder notification = buildNotification(payload, /*isIncoming=*/ false);
    notificationManager.notify((int) payload.getId(), notification.build());

    // Add it to the tracking list so we can update it.
    outgoingPayloads.put(payload.getId(), notification);
  }

  private NotificationCompat.Builder buildNotification(Payload payload, boolean isIncoming) {
    NotificationCompat.Builder notification =
        new NotificationCompat.Builder(context)
            .setContentTitle(isIncoming ? "Receiving..." : "Sending...");
    boolean indeterminate = false;
    if (payload.getType() == Payload.Type.STREAM) {
      // We can only show indeterminate progress for stream payloads.
      indeterminate = true;
    }
    notification.setProgress(100, 0, indeterminate);
    return notification;
  }

  @Override
  public void onPayloadReceived(String endpointId, Payload payload) {
    if (payload.getType() == Payload.Type.BYTES) {
      // No need to track progress for bytes.
      return;
    }

    // Build and start showing the notification.
    NotificationCompat.Builder notification = buildNotification(payload, true /*isIncoming*/);
    notificationManager.notify((int) payload.getId(), notification.build());

    // Add it to the tracking list so we can update it.
    incomingPayloads.put(payload.getId(), notification);
  }

  @Override
  public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) {
    long payloadId = update.getPayloadId();
    NotificationCompat.Builder notification = null;
    if (incomingPayloads.containsKey(payloadId)) {
      notification = incomingPayloads.get(payloadId);
      if (update.getStatus() != PayloadTransferUpdate.Status.IN_PROGRESS) {
        // This is the last update, so we no longer need to keep track of this notification.
        incomingPayloads.remove(payloadId);
      }
    } else if (outgoingPayloads.containsKey(payloadId)) {
      notification = outgoingPayloads.get(payloadId);
      if (update.getStatus() != PayloadTransferUpdate.Status.IN_PROGRESS) {
        // This is the last update, so we no longer need to keep track of this notification.
        outgoingPayloads.remove(payloadId);
      }
    }

    if (notification == null) {
      return;
    }

    switch (update.getStatus()) {
      case PayloadTransferUpdate.Status.IN_PROGRESS:
        long size = update.getTotalBytes();
        if (size == -1) {
          // This is a stream payload, so we don't need to update anything at this point.
          return;
        }
        int percentTransferred =
            (int) (100.0 * (update.getBytesTransferred() / (double) update.getTotalBytes()));
        notification.setProgress(100, percentTransferred, /* indeterminate= */ false);
        break;
      case PayloadTransferUpdate.Status.SUCCESS:
        // SUCCESS always means that we transferred 100%.
        notification
            .setProgress(100, 100, /* indeterminate= */ false)
            .setContentText("Transfer complete!");
        break;
      case PayloadTransferUpdate.Status.FAILURE:
      case PayloadTransferUpdate.Status.CANCELED:
        notification.setProgress(0, 0, false).setContentText("Transfer failed");
        break;
      default:
        // Unknown status.
    }

    notificationManager.notify((int) payloadId, notification.build());
  }
}