Exemplos de código do AndroidAndroid code examples

Este tópico apresenta-lhe elementos de código importantes para a versão Android do SDK RMS.This topic will introduce you to important code elements for the Android version of the RMS SDK.

Nota: no código de exemplo e nas descrições que se seguem, utilizamos o termo MSIPC (Microsoft Information Protection and Control) para referenciar o processo de cliente.Note In the example code and descriptions that follow, we use the term MSIPC (Microsoft Information Protection and Control) to reference the client process.

Utilizar o SDK Microsoft Rights Management 4.2 – cenários principaisUsing the Microsoft Rights Management SDK 4.2 - key scenarios

Seguem-se exemplos de código de uma aplicação de exemplo maior que representam cenários de desenvolvimento importantes para se orientar neste SDK.Following are code examples from a larger sample application representing development scenarios important to your orientation to this SDK. Estes demonstram a utilização do formato de Ficheiro Protegido da Microsoft referido como ficheiro protegido, a utilização de formatos de ficheiros protegidos personalizados e a utilização de controlos de IU personalizados.These demonstrate; use of Microsoft Protected File format referred to as protected file, use of custom protected file formats, and use of custom UI controls.

A aplicação de exemplo, MSIPCSampleApp, está disponível para utilização com este SDK para o sistema operativo Android.The sample application, MSIPCSampleApp, is available for use with this SDK for the Android operating system. Consulte rms-sdk-ui-for-android no GitHub para ter acesso a esta aplicação de exemplo.See rms-sdk-ui-for-android on GitHub for access to this sample application.

Cenário: consumir um ficheiro de RMS protegidoScenario: Consume an RMS protected file

  • Passo 1: criar um ProtectedFileInputStreamStep 1: Create a ProtectedFileInputStream

    Origem: MsipcAuthenticationCallback.javaSource: MsipcAuthenticationCallback.java

    Descrição: instanciar um objeto ProtectedFileInputStream através do respetivo método de criação que implementa o serviço de autenticação através do AuthenticationRequestCallback para obter um token transferido de uma instância de AuthenticationRequestCallback como o parâmetro mRmsAuthCallback para a API de MSIPC.Description: Instantiate a ProtectedFileInputStream object, through its create method which implements service authentication using the AuthenticationRequestCallback to get a token by passing an instance of AuthenticationRequestCallback, as the parameter mRmsAuthCallback, to the MSIPC API. Consulte a chamada para ProtectedFileInputStream.create perto do fim da seguinte secção de código de exemplo.See the call to ProtectedFileInputStream.create near the end of the following example code section.

    public void startContentConsumptionFromPtxtFileFormat(InputStream inputStream)
    {
        CreationCallback<ProtectedFileInputStream> protectedFileInputStreamCreationCallback =
          new CreationCallback<ProtectedFileInputStream>()
        {
            @Override
            public Context getContext()
            {
               …
           }
    
            @Override
            public void onCancel()
            {
               …
            }
    
            @Override
            public void onFailure(ProtectionException e)
            {
               …
            }
    
            @Override
            public void onSuccess(ProtectedFileInputStream protectedFileInputStream)
            {
               …
               …
                byte[] dataChunk = new byte[16384];
                try
                {
                    while ((nRead = protectedFileInputStream.read(dataChunk, 0,
                            dataChunk.length)) != -1)
                    {
                        …
                    }
                     …
                    protectedFileInputStream.close();
                }
                catch (IOException e)
                {
                  …
                }  
          }
        };
        try
        {
           …
            ProtectedFileInputStream.create(inputStream, null, mRmsAuthCallback,
                                            PolicyAcquisitionFlags.NONE,
                                            protectedFileInputStreamCreationCallback);
        }
        catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e)
        {
            …
        }
    }
    
  • Passo 2: configurar a autenticação com a Active Directory Authentication Library (ADAL).Step 2: Setup authentication using the Active Directory Authentication Library (ADAL).

    Origem: MsipcAuthenticationCallback.java.Source: MsipcAuthenticationCallback.java.

    Descrição: neste passo, verá a ADAL utilizada para implementar um AuthenticationRequestCallback com parâmetros de autenticação de exemplo.Description: In this step you will see ADAL used to implement an AuthenticationRequestCallback with example authentication parameters. Para obter mais informações sobre a utilização da ADAL, consulte Biblioteca de Autenticação do Azure AD (ADAL).For more information on using ADAL, see the Azure AD Authentication Library (ADAL).

    class MsipcAuthenticationCallback implements AuthenticationRequestCallback
    {

    …

    @Override
    public void getToken(Map<String, String> authenticationParametersMap,
                         final AuthenticationCompletionCallback authenticationCompletionCallbackToMsipc)
    {
        String authority = authenticationParametersMap.get("oauth2.authority");
        String resource = authenticationParametersMap.get("oauth2.resource");
        String userId = authenticationParametersMap.get("userId");
        final String userHint = (userId == null)? "" : userId;
        AuthenticationContext authenticationContext = App.getInstance().getAuthenticationContext();
        if (authenticationContext == null || !authenticationContext.getAuthority().equalsIgnoreCase(authority))
        {
            try
            {
                authenticationContext = new AuthenticationContext(App.getInstance().getApplicationContext(), authority, …);
                App.getInstance().setAuthenticationContext(authenticationContext);
            }
            catch (NoSuchAlgorithmException e)
            {
                …
                authenticationCompletionCallbackToMsipc.onFailure();
            }
            catch (NoSuchPaddingException e)
            {
                …
                authenticationCompletionCallbackToMsipc.onFailure();
            }
       }
        App.getInstance().getAuthenticationContext().acquireToken(mParentActivity, resource, mClientId, mRedirectURI, userId, mPromptBehavior,
                       "&USERNAME=" + userHint, new AuthenticationCallback<AuthenticationResult>()
                        {
                            @Override
                            public void onError(Exception exc)
                            {
                                …
                                if (exc instanceof AuthenticationCancelError)
                                {
                                     …
                                    authenticationCompletionCallbackToMsipc.onCancel();
                                }
                                else
                                {
                                     …
                                    authenticationCompletionCallbackToMsipc.onFailure();
                                }
                            }

                            @Override
                            public void onSuccess(AuthenticationResult result)
                            {
                                …
                                if (result == null || result.getAccessToken() == null
                                        || result.getAccessToken().isEmpty())
                                {
                                     …
                                }
                                else
                                {
                                    // request is successful
                                    …
                                    authenticationCompletionCallbackToMsipc.onSuccess(result.getAccessToken());
                                }
                            }
                        }

                        );
                  }
  • Passo 3: verificar se o direito Editar existe para o utilizador com estes conteúdos através do método UserPolicy.accessCheck.Step 3: Check if the Edit right exists for this user with this content via the UserPolicy.accessCheck method.

    Origem: TextEditorFragment.javaSource: TextEditorFragment.java

     //check if user has edit rights and apply enforcements
            if (!mUserPolicy.accessCheck(EditableDocumentRights.Edit))
            {
                mTextEditor.setFocusableInTouchMode(false);
                mTextEditor.setFocusable(false);
                mTextEditor.setEnabled(false);
                …
            }

Cenário: criar um novo ficheiro protegido através de um modeloScenario: Create a new protected file using a template

Este cenário começa com a obtenção de uma lista de modelo ao selecionar o primeiro para criar uma política e, em seguida, ao cria e escreve no novo ficheiro protegido.This scenario begins with getting a list of templates, selecting the first one to create a policy, then creates and writes to the new protected file.

  • Passo 1: obter a lista de modelos através de um objeto TemplateDescriptor.Step 1: Get list of templates via a TemplateDescriptor object.

    Origem: MsipcTaskFragment.javaSource: MsipcTaskFragment.java

<span data-ttu-id="6cd3e-126">CreationCallback<List<TemplateDescriptor>> getTemplatesCreationCallback = new CreationCallback<List<TemplateDescriptor>>() { @Override public Context getContext() { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-126">CreationCallback<List<TemplateDescriptor>> getTemplatesCreationCallback = new CreationCallback<List<TemplateDescriptor>>() { @Override public Context getContext() { …</span></span>
      <span data-ttu-id="6cd3e-127">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-127">}</span></span>

      @Override
      public void onCancel()
      {
          …
      }

      @Override
      public void onFailure(ProtectionException e)
      {
          …
      }

      @Override
      public void onSuccess(List<TemplateDescriptor> templateDescriptors)
      {
         …
      }
  <span data-ttu-id="6cd3e-128">}; try { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-128">}; try { …</span></span>
      <span data-ttu-id="6cd3e-129">mIAsyncControl = TemplateDescriptor.getTemplates(emailId, mRmsAuthCallback, getTemplatesCreationCallback); } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-129">mIAsyncControl = TemplateDescriptor.getTemplates(emailId, mRmsAuthCallback, getTemplatesCreationCallback); } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) { …</span></span>
  <span data-ttu-id="6cd3e-130">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-130">}</span></span>
  • Passo 2: criar um UserPolicy com o primeiro modelo na lista.Step 2: Create a UserPolicy using the first template in the list.

    Origem: MsipcTaskFragment.javaSource: MsipcTaskFragment.java

  <span data-ttu-id="6cd3e-133">CreationCallback<UserPolicy> userPolicyCreationCallback = new CreationCallback<UserPolicy>() { @Override public Context getContext() { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-133">CreationCallback<UserPolicy> userPolicyCreationCallback = new CreationCallback<UserPolicy>() { @Override public Context getContext() { …</span></span>
      <span data-ttu-id="6cd3e-134">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-134">}</span></span>

      @Override
      public void onCancel()
      {
          …
      }

      @Override
      public void onFailure(ProtectionException e)
      {
          …
      }

      @Override
      public void onSuccess(final UserPolicy item)
      {
          …
      }
  <span data-ttu-id="6cd3e-135">}; try { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-135">}; try { …</span></span>
      <span data-ttu-id="6cd3e-136">mIAsyncControl = UserPolicy.create((TemplateDescriptor)selectedDescriptor, mEmailId, mRmsAuthCallback, UserPolicyCreationFlags.NONE, userPolicyCreationCallback); …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-136">mIAsyncControl = UserPolicy.create((TemplateDescriptor)selectedDescriptor, mEmailId, mRmsAuthCallback, UserPolicyCreationFlags.NONE, userPolicyCreationCallback); …</span></span>
  <span data-ttu-id="6cd3e-137">} catch (InvalidParameterException e) { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-137">} catch (InvalidParameterException e) { …</span></span>
  <span data-ttu-id="6cd3e-138">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-138">}</span></span>
<span data-ttu-id="6cd3e-141">private void createPTxt(final byte[] contentToProtect) { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-141">private void createPTxt(final byte[] contentToProtect) { …</span></span>
        <span data-ttu-id="6cd3e-142">CreationCallback<ProtectedFileOutputStream> protectedFileOutputStreamCreationCallback = new CreationCallback<ProtectedFileOutputStream>() { @Override public Context getContext() { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-142">CreationCallback<ProtectedFileOutputStream> protectedFileOutputStreamCreationCallback = new CreationCallback<ProtectedFileOutputStream>() { @Override public Context getContext() { …</span></span>
            <span data-ttu-id="6cd3e-143">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-143">}</span></span>

            @Override
            public void onCancel()
            {
             …
            }

            @Override
            public void onFailure(ProtectionException e)
            {
             …
            }

            @Override
            public void onSuccess(ProtectedFileOutputStream protectedFileOutputStream)
            {
                try
                {
                    // write to this stream
                    protectedFileOutputStream.write(contentToProtect);
                    protectedFileOutputStream.flush();
                    protectedFileOutputStream.close();
                    …
                }
                catch (IOException e)
                {
                    …
                }
            }
        };
        try
        {
            File file = new File(filePath);
            outputStream = new FileOutputStream(file);
            mIAsyncControl = ProtectedFileOutputStream.create(outputStream, mUserPolicy, originalFileExtension,
                    protectedFileOutputStreamCreationCallback);
        }
        catch (FileNotFoundException e)
        {
             …
        }
        catch (InvalidParameterException e)
        {
             …
        }
    <span data-ttu-id="6cd3e-144">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-144">}</span></span>

Cenário: abrir um ficheiro protegido personalizadoScenario: Open a custom protected file

  • Passo 1: criar um UserPolicy a partir de um serializedContentPolicy.Step 1: Create a UserPolicy from a serializedContentPolicy.

    Origem: MsipcTaskFragment.javaSource: MsipcTaskFragment.java

<span data-ttu-id="6cd3e-148">CreationCallback<UserPolicy> userPolicyCreationCallbackFromSerializedContentPolicy = new CreationCallback<UserPolicy>() { @Override public void onSuccess(UserPolicy userPolicy) { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-148">CreationCallback<UserPolicy> userPolicyCreationCallbackFromSerializedContentPolicy = new CreationCallback<UserPolicy>() { @Override public void onSuccess(UserPolicy userPolicy) { …</span></span>
            <span data-ttu-id="6cd3e-149">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-149">}</span></span>

            @Override
            public void onFailure(ProtectionException e)
            {
              …
            }

            @Override
            public void onCancel()
            {
              …
            }

            @Override
            public Context getContext()
            {
              …
            }
        };


<span data-ttu-id="6cd3e-150">try {   ...</span><span class="sxs-lookup"><span data-stu-id="6cd3e-150">try {   ...</span></span>

  <span data-ttu-id="6cd3e-151">// Read the serializedContentPolicyLength from the inputStream.</span><span class="sxs-lookup"><span data-stu-id="6cd3e-151">// Read the serializedContentPolicyLength from the inputStream.</span></span>
  <span data-ttu-id="6cd3e-152">long serializedContentPolicyLength = readUnsignedInt(inputStream);</span><span class="sxs-lookup"><span data-stu-id="6cd3e-152">long serializedContentPolicyLength = readUnsignedInt(inputStream);</span></span>

  <span data-ttu-id="6cd3e-153">// Read the PL bytes from the input stream using the PL size.</span><span class="sxs-lookup"><span data-stu-id="6cd3e-153">// Read the PL bytes from the input stream using the PL size.</span></span>
  <span data-ttu-id="6cd3e-154">byte[] serializedContentPolicy = new byte[(int)serializedContentPolicyLength]; inputStream.read(serializedContentPolicy);</span><span class="sxs-lookup"><span data-stu-id="6cd3e-154">byte[] serializedContentPolicy = new byte[(int)serializedContentPolicyLength]; inputStream.read(serializedContentPolicy);</span></span>

  <span data-ttu-id="6cd3e-155">...</span><span class="sxs-lookup"><span data-stu-id="6cd3e-155">...</span></span>

  <span data-ttu-id="6cd3e-156">UserPolicy.acquire(serializedContentPolicy, null, mRmsAuthCallback, PolicyAcquisitionFlags.NONE,           userPolicyCreationCallbackFromSerializedContentPolicy); } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) {   ... } catch (IOException e) {   ... }</span><span class="sxs-lookup"><span data-stu-id="6cd3e-156">UserPolicy.acquire(serializedContentPolicy, null, mRmsAuthCallback, PolicyAcquisitionFlags.NONE,           userPolicyCreationCallbackFromSerializedContentPolicy); } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) {   ... } catch (IOException e) {   ... }</span></span>
  <span data-ttu-id="6cd3e-159">CreationCallback<CustomProtectedInputStream> customProtectedInputStreamCreationCallback = new CreationCallback<CustomProtectedInputStream>() { @Override public Context getContext() { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-159">CreationCallback<CustomProtectedInputStream> customProtectedInputStreamCreationCallback = new CreationCallback<CustomProtectedInputStream>() { @Override public Context getContext() { …</span></span>
     <span data-ttu-id="6cd3e-160">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-160">}</span></span>

     @Override
     public void onCancel()
     {
         …
     }

     @Override
     public void onFailure(ProtectionException e)
     {
         …
     }

     @Override
     public void onSuccess(CustomProtectedInputStream customProtectedInputStream)
     {
        …

         byte[] dataChunk = new byte[16384];
         try
         {
             while ((nRead = customProtectedInputStream.read(dataChunk, 0, dataChunk.length)) != -1)
             {
                  …
             }
              …
             customProtectedInputStream.close();
         }
         catch (IOException e)
         {
            …
         }
         …
     }
 <span data-ttu-id="6cd3e-161">};</span><span class="sxs-lookup"><span data-stu-id="6cd3e-161">};</span></span>

<span data-ttu-id="6cd3e-162">try {  ...</span><span class="sxs-lookup"><span data-stu-id="6cd3e-162">try {  ...</span></span>

  <span data-ttu-id="6cd3e-163">// Retrieve the encrypted content size.</span><span class="sxs-lookup"><span data-stu-id="6cd3e-163">// Retrieve the encrypted content size.</span></span>
  <span data-ttu-id="6cd3e-164">long encryptedContentLength = readUnsignedInt(inputStream);</span><span class="sxs-lookup"><span data-stu-id="6cd3e-164">long encryptedContentLength = readUnsignedInt(inputStream);</span></span>

  <span data-ttu-id="6cd3e-165">updateTaskStatus(new TaskStatus(TaskState.Starting, "Consuming content", true));</span><span class="sxs-lookup"><span data-stu-id="6cd3e-165">updateTaskStatus(new TaskStatus(TaskState.Starting, "Consuming content", true));</span></span>

  <span data-ttu-id="6cd3e-166">CustomProtectedInputStream.create(userPolicy, inputStream,                                 encryptedContentLength,                                 customProtectedInputStreamCreationCallback); } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) {  ... } catch (IOException e) {  ... }</span><span class="sxs-lookup"><span data-stu-id="6cd3e-166">CustomProtectedInputStream.create(userPolicy, inputStream,                                 encryptedContentLength,                                 customProtectedInputStreamCreationCallback); } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) {  ... } catch (IOException e) {  ... }</span></span>
<span data-ttu-id="6cd3e-169">@Override public void onSuccess(CustomProtectedInputStream customProtectedInputStream) {  mUserPolicy = customProtectedInputStream.getUserPolicy();  ByteArrayOutputStream buffer = new ByteArrayOutputStream();</span><span class="sxs-lookup"><span data-stu-id="6cd3e-169">@Override public void onSuccess(CustomProtectedInputStream customProtectedInputStream) {  mUserPolicy = customProtectedInputStream.getUserPolicy();  ByteArrayOutputStream buffer = new ByteArrayOutputStream();</span></span>

  <span data-ttu-id="6cd3e-170">int nRead;</span><span class="sxs-lookup"><span data-stu-id="6cd3e-170">int nRead;</span></span>                      
  <span data-ttu-id="6cd3e-171">byte[] dataChunk = new byte[16384];</span><span class="sxs-lookup"><span data-stu-id="6cd3e-171">byte[] dataChunk = new byte[16384];</span></span>

  <span data-ttu-id="6cd3e-172">try  {    while ((nRead = customProtectedInputStream.read(dataChunk, 0,                                                        dataChunk.length)) != -1)    {       buffer.write(dataChunk, 0, nRead);    }</span><span class="sxs-lookup"><span data-stu-id="6cd3e-172">try  {    while ((nRead = customProtectedInputStream.read(dataChunk, 0,                                                        dataChunk.length)) != -1)    {       buffer.write(dataChunk, 0, nRead);    }</span></span>

    <span data-ttu-id="6cd3e-173">buffer.flush();    mDecryptedContent = new String(buffer.toByteArray(), Charset.forName("UTF-8"));</span><span class="sxs-lookup"><span data-stu-id="6cd3e-173">buffer.flush();    mDecryptedContent = new String(buffer.toByteArray(), Charset.forName("UTF-8"));</span></span>

    <span data-ttu-id="6cd3e-174">buffer.close();    customProtectedInputStream.close();  }  catch (IOException e)  {    ...  } }</span><span class="sxs-lookup"><span data-stu-id="6cd3e-174">buffer.close();    customProtectedInputStream.close();  }  catch (IOException e)  {    ...  } }</span></span>

Cenário: criar um ficheiro protegido personalizado utilizando uma política personalizada (ad hoc)Scenario: Create a custom protected file using a custom (ad-hoc) policy

  • Passo 1: com um endereço de e-mail fornecido pelo utilizador, criar um descritor de política.Step 1: With an email address provided by the user, create a policy descriptor.

    Origem: MsipcTaskFragment.javaSource: MsipcTaskFragment.java

    Descrição: na prática, seria possível criar os seguintes objetos com entradas do utilizador a partir da interface do dispositivo; UserRights e PolicyDescriptor.Description: In practice the following objects would be created by using user inputs from the device interface; UserRights and PolicyDescriptor.

  <span data-ttu-id="6cd3e-179">// create userRights list   UserRights userRights = new UserRights(Arrays.asList("consumer@domain.com"),     Arrays.asList( CommonRights.View, EditableDocumentRights.Print));   ArrayList<UserRights> usersRigthsList = new ArrayList<UserRights>();   usersRigthsList.add(userRights);</span><span class="sxs-lookup"><span data-stu-id="6cd3e-179">// create userRights list   UserRights userRights = new UserRights(Arrays.asList("consumer@domain.com"),     Arrays.asList( CommonRights.View, EditableDocumentRights.Print));   ArrayList<UserRights> usersRigthsList = new ArrayList<UserRights>();   usersRigthsList.add(userRights);</span></span>

  <span data-ttu-id="6cd3e-180">// Create PolicyDescriptor using userRights list   PolicyDescriptor policyDescriptor = PolicyDescriptor.createPolicyDescriptorFromUserRights(                                                          usersRigthsList);   policyDescriptor.setOfflineCacheLifetimeInDays(10);   policyDescriptor.setContentValidUntil(new Date());</span><span class="sxs-lookup"><span data-stu-id="6cd3e-180">// Create PolicyDescriptor using userRights list   PolicyDescriptor policyDescriptor = PolicyDescriptor.createPolicyDescriptorFromUserRights(                                                          usersRigthsList);   policyDescriptor.setOfflineCacheLifetimeInDays(10);   policyDescriptor.setContentValidUntil(new Date());</span></span>
  • Passo 2: criar um UserPolicy personalizado do descritor de política selectedDescriptor.Step 2: Create a custom UserPolicy from the policy descriptor, selectedDescriptor.

    Origem: MsipcTaskFragment.javaSource: MsipcTaskFragment.java

   <span data-ttu-id="6cd3e-183">mIAsyncControl = UserPolicy.create((PolicyDescriptor)selectedDescriptor,                                          mEmailId, mRmsAuthCallback,                                          UserPolicyCreationFlags.NONE,                                          userPolicyCreationCallback);</span><span class="sxs-lookup"><span data-stu-id="6cd3e-183">mIAsyncControl = UserPolicy.create((PolicyDescriptor)selectedDescriptor,                                          mEmailId, mRmsAuthCallback,                                          UserPolicyCreationFlags.NONE,                                          userPolicyCreationCallback);</span></span>
<span data-ttu-id="6cd3e-186">File file = new File(filePath); final OutputStream outputStream = new FileOutputStream(file); CreationCallback<CustomProtectedOutputStream> customProtectedOutputStreamCreationCallback = new CreationCallback<CustomProtectedOutputStream>() { @Override public Context getContext() { …</span><span class="sxs-lookup"><span data-stu-id="6cd3e-186">File file = new File(filePath); final OutputStream outputStream = new FileOutputStream(file); CreationCallback<CustomProtectedOutputStream> customProtectedOutputStreamCreationCallback = new CreationCallback<CustomProtectedOutputStream>() { @Override public Context getContext() { …</span></span>
        <span data-ttu-id="6cd3e-187">}</span><span class="sxs-lookup"><span data-stu-id="6cd3e-187">}</span></span>

        @Override
        public void onCancel()
        {
          …
        }

        @Override
        public void onFailure(ProtectionException e)
        {
          …
        }

        @Override
        public void onSuccess(CustomProtectedOutputStream protectedOutputStream)
        {
            try
            {
                // write serializedContentPolicy
                byte[] serializedContentPolicy = mUserPolicy.getSerializedContentPolicy();
                writeLongAsUnsignedIntToStream(outputStream, serializedContentPolicy.length);
                outputStream.write(serializedContentPolicy);
                // write encrypted content
                if (contentToProtect != null)
                {
                    writeLongAsUnsignedIntToStream(outputStream,
                            CustomProtectedOutputStream.getEncryptedContentLength(contentToProtect.length,
                                    protectedOutputStream.getUserPolicy()));
                    protectedOutputStream.write(contentToProtect);
                    protectedOutputStream.flush();
                    protectedOutputStream.close();
                }
                else
                {
                    outputStream.flush();
                    outputStream.close();
                }
                …
            }
            catch (IOException e)
            {
              …
            }
        }
    };
    try
    {
        mIAsyncControl = CustomProtectedOutputStream.create(outputStream, mUserPolicy,
                customProtectedOutputStreamCreationCallback);
    }
    catch (InvalidParameterException e)
    {
      …
    }

ComentáriosComments

Antes de inserir um comentário, pedimos-lhe que reveja as nossas Regras básicas.Before commenting, we ask that you review our House rules.