├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── NOTICES.md ├── README-Localized ├── README-de-de.md ├── README-es-es.md ├── README-fr-fr.md ├── README-ja-jp.md ├── README-pt-br.md ├── README-ru-ru.md ├── README-zh-cn.md └── README-zh-tw.md ├── README.md ├── app ├── .gitignore ├── build.gradle ├── gradle.properties ├── proguard-rules.pro └── src │ ├── androidTest │ ├── getTestConfig.bat │ └── getTestConfig.sh │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── microsoft │ │ │ └── graph │ │ │ └── connect │ │ │ ├── AuthenticationManager.java │ │ │ ├── Connect.java │ │ │ ├── ConnectActivity.java │ │ │ ├── Constants.java │ │ │ ├── GraphServiceClientManager.java │ │ │ ├── GraphServiceController.java │ │ │ ├── MSALAuthenticationCallback.java │ │ │ ├── SendMailActivity.java │ │ │ ├── TokenNotFoundException.java │ │ │ ├── UiBehavior.java │ │ │ └── util │ │ │ ├── IManifestReader.java │ │ │ └── ManifestReader.java │ └── res │ │ ├── drawable │ │ ├── ic_launcher.xml │ │ └── test.jpg │ │ ├── layout │ │ ├── activity_connect.xml │ │ └── activity_send_mail.xml │ │ ├── menu │ │ └── send_mail.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── microsoft │ └── graph │ └── connect │ ├── AuthenticationManagerUnitTests.java │ ├── ConfigurationTests.java │ └── GraphServiceControllerUnitTests.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── readme-images ├── Android-Connect-Constants.png ├── O365-Android-Connect-video_play_icon.png ├── aad-application-id.PNG ├── aad-implicit-grant.png ├── aad-portal-app-registrations.png ├── aad-redirect-uri-public-client.PNG └── aad-register-an-app.PNG └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.ap_ 2 | *.apk 3 | *.class 4 | *.dex 5 | *.iml 6 | *.ipr 7 | *.iws 8 | .DS_Store 9 | .classpath 10 | .gradle 11 | .idea 12 | .project 13 | /.idea/libraries 14 | /.idea/workspace.xml 15 | /build 16 | /captures 17 | /local.properties 18 | Thumbs.db 19 | bin/ 20 | build/ 21 | gen/ 22 | out/ 23 | testConfig.json 24 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribute to this documentation 2 | 3 | Thank you for your interest in our documentation! 4 | 5 | * [Ways to contribute](#ways-to-contribute) 6 | * [Contribute using GitHub](#contribute-using-github) 7 | * [Contribute using Git](#contribute-using-git) 8 | * [How to use Markdown to format your topic](#how-to-use-markdown-to-format-your-topic) 9 | * [FAQ](#faq) 10 | * [More resources](#more-resources) 11 | 12 | ## Ways to contribute 13 | 14 | Here are some ways you can contribute to this documentation: 15 | 16 | * To make small changes to an article, [Contribute using GitHub](#contribute-using-github). 17 | * To make large changes, or changes that involve code, [Contribute using Git](#contribute-using-git). 18 | * Report documentation bugs via GitHub Issues 19 | * Request new documentation at the [Office Developer Platform UserVoice](http://officespdev.uservoice.com) site. 20 | 21 | ## Contribute using GitHub 22 | 23 | Use GitHub to contribute to this documentation without having to clone the repo to your desktop. This is the easiest way to create a pull request in this repository. Use this method to make a minor change that doesn't involve code changes. 24 | 25 | **Note** Using this method allows you to contribute to one article at a time. 26 | 27 | ### To Contribute using GitHub 28 | 29 | 1. Find the article you want to contribute to on GitHub. 30 | 31 | If the article is in MSDN, choose the **suggest and submit changes** link in the **Contribute to this content** section and you'll be taken to the same article on GitHub. 32 | 2. Once you are on the article in GitHub, sign in to GitHub (get a free account [Join GitHub](https://github.com/join). 33 | 3. Choose the **pencil icon** (edit the file in your fork of this project) and make your changes in the **<>Edit file** window. 34 | 4. Scroll to the bottom and enter a description. 35 | 5. Choose **Propose file change**>**Create pull request**. 36 | 37 | You now have successfully submitted a pull request. Pull requests are typically reviewed within 10 business days. 38 | 39 | 40 | ## Contribute using Git 41 | 42 | Use Git to contribute substantive changes, such as: 43 | 44 | * Contributing code. 45 | * Contributing changes that affect meaning. 46 | * Contributing large changes to text. 47 | * Adding new topics. 48 | 49 | ### To Contribute using Git 50 | 51 | 1. If you don't have a GitHub account, set one up at [GitHub](https://github.com/join). 52 | 2. After you have an account, install Git on your computer. Follow the steps in [Setting up Git Tutorial](https://help.github.com/articles/set-up-git/). 53 | 3. To submit a pull request using Git, follow the steps in [Use GitHub, Git, and this repository](#use-github-git-and-this-repository). 54 | 4. You will be asked to sign the Contributor's License Agreement if you are: 55 | 56 | * A member of the Microsoft Open Technologies group. 57 | * A contributors who doesn't work for Microsoft. 58 | 59 | As a community member, you must sign the Contribution License Agreement (CLA) before you can contribute large submissions to a project. You only need to complete and submit the documentation once. Carefully review the document. You may be required to have your employer sign the document. 60 | 61 | Signing the CLA does not grant you rights to commit to the main repository, but it does mean that the Office Developer and Office Developer Content Publishing teams will be able to review and approve your contributions. You will be credited for your submissions. 62 | 63 | Pull requests are typically reviewed within 10 business days. 64 | 65 | ## Use GitHub, Git, and this repository 66 | 67 | **Note:** Most of the information in this section can be found in [GitHub Help] articles. If you're familiar with Git and GitHub, skip to the **Contribute and edit content** section for the specifics of the code/content flow of this repository. 68 | 69 | ### To set up your fork of the repository 70 | 71 | 1. Set up a GitHub account so you can contribute to this project. If you haven't done this, go to [GitHub](https://github.com/join) and do it now. 72 | 2. Install Git on your computer. Follow the steps in the [Setting up Git Tutorial] [Set Up Git]. 73 | 3. Create your own fork of this repository. To do this, at the top of the page, choose the **Fork** button. 74 | 4. Copy your fork to your computer. To do this, open Git Bash. At the command prompt enter: 75 | 76 | git clone https://github.com//.git 77 | 78 | Next, create a reference to the root repository by entering these commands: 79 | 80 | cd 81 | git remote add upstream https://github.com/microsoftgraph/.git 82 | git fetch upstream 83 | 84 | Congratulations! You've now set up your repository. You won't need to repeat these steps again. 85 | 86 | ### Contribute and edit content 87 | 88 | To make the contribution process as seamless as possible, follow these steps. 89 | 90 | #### To contribute and edit content 91 | 92 | 1. Create a new branch. 93 | 2. Add new content or edit existing content. 94 | 3. Submit a pull request to the main repository. 95 | 4. Delete the branch. 96 | 97 | **Important** Limit each branch to a single concept/article to streamline the work flow and reduce the chance of merge conflicts. Content appropriate for a new branch includes: 98 | 99 | * A new article. 100 | * Spelling and grammar edits. 101 | * Applying a single formatting change across a large set of articles (for example, applying a new copyright footer). 102 | 103 | #### To create a new branch 104 | 105 | 1. Open Git Bash. 106 | 2. At the Git Bash command prompt, type `git pull upstream master:`. This creates a new branch locally that is copied from the latest MicrosoftGraph master branch. 107 | 3. At the Git Bash command prompt, type `git push origin `. This alerts GitHub to the new branch. You should now see the new branch in your fork of the repository on GitHub. 108 | 4. At the Git Bash command prompt, type `git checkout ` to switch to your new branch. 109 | 110 | #### Add new content or edit existing content 111 | 112 | You navigate to the repository on your computer by using File Explorer. The repository files are in `C:\Users\\`. 113 | 114 | To edit files, open them in an editor of your choice and modify them. To create a new file, use the editor of your choice and save the new file in the appropriate location in your local copy of the repository. While working, save your work frequently. 115 | 116 | The files in `C:\Users\\` are a working copy of the new branch that you created in your local repository. Changing anything in this folder doesn't affect the local repository until you commit a change. To commit a change to the local repository, type the following commands in GitBash: 117 | 118 | git add . 119 | git commit -v -a -m "" 120 | 121 | The `add` command adds your changes to a staging area in preparation for committing them to the repository. The period after the `add` command specifies that you want to stage all of the files that you added or modified, checking subfolders recursively. (If you don't want to commit all of the changes, you can add specific files. You can also undo a commit. For help, type `git add -help` or `git status`.) 122 | 123 | The `commit` command applies the staged changes to the repository. The switch `-m` means you are providing the commit comment in the command line. The -v and -a switches can be omitted. The -v switch is for verbose output from the command, and -a does what you already did with the add command. 124 | 125 | You can commit multiple times while you are doing your work, or you can commit once when you're done. 126 | 127 | #### Submit a pull request to the main repository 128 | 129 | When you're finished with your work and are ready to have it merged into the main repository, follow these steps. 130 | 131 | #### To submit a pull request to the main repository 132 | 133 | 1. In the Git Bash command prompt, type `git push origin `. In your local repository, `origin` refers to your GitHub repository that you cloned the local repository from. This command pushes the current state of your new branch, including all commits made in the previous steps, to your GitHub fork. 134 | 2. On the GitHub site, navigate in your fork to the new branch. 135 | 3. Choose the **Pull Request** button at the top of the page. 136 | 4. Verify the Base branch is `microsoftgraph/@master` and the Head branch is `/@`. 137 | 5. Choose the **Update Commit Range** button. 138 | 6. Add a title to your pull request, and describe all the changes you're making. 139 | 7. Submit the pull request. 140 | 141 | One of the site administrators will process your pull request. Your pull request will surface on the microsoftgraph/ site under Issues. When the pull request is accepted, the issue will be resolved. 142 | 143 | #### Create a new branch after merge 144 | 145 | After a branch is successfully merged (that is, your pull request is accepted), don't continue working in that local branch. This can lead to merge conflicts if you submit another pull request. To do another update, create a new local branch from the successfully merged upstream branch, and then delete your initial local branch. 146 | 147 | For example, if your local branch X was successfully merged into the OfficeDev/microsoft-graph-docs master branch and you want to make additional updates to the content that was merged. Create a new local branch, X2, from the OfficeDev/microsoft-graph-docs master branch. To do this, open GitBash and execute the following commands: 148 | 149 | cd microsoft-graph-docs 150 | git pull upstream master:X2 151 | git push origin X2 152 | 153 | You now have local copies (in a new local branch) of the work that you submitted in branch X. The X2 branch also contains all the work other writers have merged, so if your work depends on others' work (for example, shared images), it is available in the new branch. You can verify that your previous work (and others' work) is in the branch by checking out the new branch... 154 | 155 | git checkout X2 156 | 157 | ...and verifying the content. (The `checkout` command updates the files in `C:\Users\\microsoft-graph-docs` to the current state of the X2 branch.) Once you check out the new branch, you can make updates to the content and commit them as usual. However, to avoid working in the merged branch (X) by mistake, it's best to delete it (see the following **Delete a branch** section). 158 | 159 | #### Delete a branch 160 | 161 | Once your changes are successfully merged into the main repository, delete the branch you used because you no longer need it. Any additional work should be done in a new branch. 162 | 163 | #### To delete a branch 164 | 165 | 1. In the Git Bash command prompt, type `git checkout master`. This ensures that you aren't in the branch to be deleted (which isn't allowed). 166 | 2. Next, at the command prompt, type `git branch -d `. This deletes the branch on your computer only if it has been successfully merged to the upstream repository. (You can override this behavior with the `–D` flag, but first be sure you want to do this.) 167 | 3. Finally, type `git push origin :` at the command prompt (a space before the colon and no space after it). This will delete the branch on your github fork. 168 | 169 | Congratulations, you have successfully contributed to the project! 170 | 171 | ## How to use Markdown to format your topic 172 | 173 | ### Article template 174 | 175 | The [markdown template](/articles/0-markdown-template-for-new-articles.md) contains the basic Markdown for a topic that includes a table of contents, sections with subheadings, links to other Office developer topics, links to other sites, bold text, italic text, numbered and bulleted lists, code snippets, and images. 176 | 177 | 178 | ### Standard Markdown 179 | 180 | All of the articles in this repository use Markdown. A complete introduction (and listing of all the syntax) can be found at [Markdown Home] []. 181 | 182 | ## FAQ 183 | 184 | ### How do I get a GitHub account? 185 | 186 | Fill out the form at [Join GitHub](https://github.com/join) to open a free GitHub account. 187 | 188 | ### Where do I get a Contributor's License Agreement? 189 | 190 | You will automatically be sent a notice that you need to sign the Contributor's License Agreement (CLA) if your pull request requires one. 191 | 192 | As a community member, **you must sign the Contribution License Agreement (CLA) before you can contribute large submissions to this project**. You only need complete and submit the documentation once. Carefully review the document. You may be required to have your employer sign the document. 193 | 194 | ### What happens with my contributions? 195 | 196 | When you submit your changes, via a pull request, our team will be notified and will review your pull request. You will receive notifications about your pull request from GitHub; you may also be notified by someone from our team if we need more information. We reserve the right to edit your submission for legal, style, clarity, or other issues. 197 | 198 | ### Can I become an approver for this repository's GitHub pull requests? 199 | 200 | Currently, we are not allowing external contributors to approve pull requests in this repository. 201 | 202 | ### How soon will I get a response about my change request or issue? 203 | 204 | We typically review pull requests and respond to issues within 10 business days. 205 | 206 | ## More resources 207 | 208 | * To learn more about Markdown, go to the Git creator's site [Daring Fireball]. 209 | * To learn more about using Git and GitHub, first check out the [GitHub Help section] [GitHub Help]. 210 | 211 | [GitHub Home]: http://github.com 212 | [GitHub Help]: http://help.github.com/ 213 | [Set Up Git]: http://help.github.com/win-set-up-git/ 214 | [Markdown Home]: http://daringfireball.net/projects/markdown/ 215 | [Daring Fireball]: http://daringfireball.net/ 216 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Microsoft. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /NOTICES.md: -------------------------------------------------------------------------------- 1 | This project includes the following third-party components: 2 | 3 | 4 | Microsoft Azure Active Directory Authentication Library (ADAL) for Android, which is Copyright (c) Microsoft Open Technologies, Inc., and is available under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 5 | 6 | Microsoft Graph SDK for Android, which is Copyright (c) Microsoft Corporation, and is available under the [MIT License](https://github.com/microsoftgraph/msgraph-sdk-android/blob/master/LICENSE). 7 | 8 | Android SDK, which is provided by the Android Open Source Project and is used according to terms described in the [Creative Commons 2.5 Attribution License](http://creativecommons.org/licenses/by/2.5/). The Android SDK is available at [http://developer.android.com/sdk/index.html](http://developer.android.com/sdk/index.html). 9 | -------------------------------------------------------------------------------- /README-Localized/README-de-de.md: -------------------------------------------------------------------------------- 1 | # Connect-Beispiel für Android unter Verwendung des Microsoft Graph-SDK 2 | 3 | 4 | >**Hinweis:** Dieses Beispiel wird gerade so aktualisiert, dass die [empfohlene Authentifizierungsbibliothek](https://docs.microsoft.com/de-de/azure/active-directory/develop/active-directory-v2-libraries#compatible-client-libraries) für Android-Apps verwendet wird. 5 | 6 | 7 | > **Sie erstellen Apps für Unternehmenskunden?** Ihre App funktioniert möglicherweise nicht, wenn Ihr Unternehmenskunde Enterprise Mobility-Sicherheitsfunktionen wie bedingten Gerätezugriff aktiviert. In diesem Fall treten bei Ihren Kunden möglicherweise Fehler auf. 8 | 9 | > Zur Unterstützung **aller Unternehmenskunden** über **alle Unternehmensszenarien** hinweg müssen Sie den Azure AD-Endpunkt verwenden und Ihr Apps mithilfe des [Azure-Verwaltungsportals](https://aka.ms/aadapplist) verwalten. Weitere Informationen finden Sie unter [Entscheiden zwischen dem Azure AD- und dem Azure AD v2.0-Endpunkt](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint). 10 | 11 | [![Microsoft Graph Connect-Beispiel](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "Klicken Sie, um das Beispiel in Aktion zu sehen.") 12 | 13 | Für die Arbeit mit Office 365-Diensten und -Daten muss jede Android-App zunächst eine Verbindung zu Microsoft Graph herstellen. In diesem Beispiel wird gezeigt, wie die Verbindung zu und dann der Aufruf einer API über das Microsoft Graph-SDK erfolgt. 14 | 15 | ## Geräteanforderungen 16 | 17 | Zum Ausführen des Connect-Beispiels muss das Gerät die folgenden Anforderungen erfüllen: 18 | 19 | * Eine Bildschirmgröße von mindestens 800 x 480 Pixel. 20 | * Android-API-Ebene 16 oder höher. 21 | 22 | ## Anforderungen 23 | 24 | Zum Verwenden des Connect-Beispiels für Android benötigen Sie Folgendes: 25 | 26 | * [Android Studio](http://developer.android.com/sdk/index.html) Version 1.0 oder höher. 27 | * [Java Development Kit (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html). 28 | 29 | 30 | ##Registrieren und Konfigurieren der App 31 | 32 | 1. Melden Sie sich beim [App-Registrierungsportal](https://apps.dev.microsoft.com/) entweder mit Ihrem persönlichen oder geschäftlichen Konto oder mit Ihrem Schulkonto an. 33 | 2. Klicken Sie auf **App hinzufügen**. 34 | 3. Geben Sie einen Namen für die App ein, und wählen Sie **Anwendung erstellen** aus. 35 | 36 | Die Registrierungsseite wird angezeigt, und die Eigenschaften der App werden aufgeführt. 37 | 38 | 4. Wählen Sie unter **Plattformen** die Option **Plattform hinzufügen** aus. 39 | 5. Wählen Sie **Mobile Anwendung** aus. 40 | 6. Kopieren Sie die **Anwendungs-ID**; Sie benötigen sie im nächsten Abschnitt. 41 | 7. Klicken Sie auf **Speichern**. 42 | 43 | ## Öffnen des Beispiels mithilfe von Android Studio 44 | 45 | 1. Installieren Sie [Android Studio](http://developer.android.com/sdk/index.html), und fügen Sie gemäß den [Anleitungen](http://developer.android.com/sdk/installing/adding-packages.html) auf „developer.android.com“ die Android SDK-Pakete hinzu. 46 | 2. Laden Sie dieses Beispiel herunter, oder klonen Sie es. 47 | 3. Starten Sie Android Studio. 48 | 1. Schließen Sie alle möglicherweise geöffneten Projekte, und wählen Sie dann **Vorhandenes Android Studio-Projekt öffnen** aus. 49 | 2. Navigieren Sie zum lokalen Repository, und wählen Sie das Projekt „Android-Connect“ aus. Klicken Sie auf **OK**. 50 | 51 | > Hinweis: In Android Studio wird die Benachrichtigung **Frameworks erkannt** angezeigt, wenn Sie das **Android-Support-Repository** nicht installiert haben. Öffnen Sie den SDK-Manager, und fügen Sie das Android-Support-Repository hinzu, um zu verhindern, dass die Benachrichtigung zu erkannten Frameworks angezeigt wird. 52 | 4. Öffnen Sie die Datei „Constants.java“. 53 | * Ersetzen Sie *ENTER_YOUR_CLIENT_ID* durch die Anwendungs-ID aus dem vorherigen Abschnitt. 54 | 55 | Nach dem Einrichten des Connect-Beispiels können Sie es auf einem Emulator oder Gerät ausführen. Wählen Sie ein Gerät mit API-Ebene 16 oder höher aus dem Dialogfeld **Gerät auswählen** aus. 56 | 57 | Weitere Informationen über das Beispiel finden Sie unter [Aufrufen von Microsoft Graph in einer Android-App](https://graph.microsoft.io/de-de/docs/platform/android). 58 | 59 | 60 | ## Mitwirkung ## 61 | 62 | Wenn Sie einen Beitrag zu diesem Beispiel leisten möchten, finden Sie unter [CONTRIBUTING.MD](/CONTRIBUTING.md) weitere Informationen. 63 | 64 | In diesem Projekt wurden die [Microsoft Open Source-Verhaltensregeln](https://opensource.microsoft.com/codeofconduct/) übernommen. Weitere Informationen finden Sie unter [Häufig gestellte Fragen zu Verhaltensregeln](https://opensource.microsoft.com/codeofconduct/faq/), oder richten Sie Ihre Fragen oder Kommentare an [opencode@microsoft.com](mailto:opencode@microsoft.com). 65 | 66 | ## Fragen und Kommentare 67 | 68 | Wir schätzen Ihr Feedback hinsichtlich des Connect-Beispiels. Sie können uns Ihre Fragen und Vorschläge über den Abschnitt [Probleme](issues) dieses Repositorys senden. 69 | 70 | Allgemeine Fragen zur Microsoft Graph-Entwicklung sollten in [Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API) gestellt werden. Stellen Sie sicher, dass Ihre Fragen oder Kommentare mit [MicrosoftGraph] und [API] markiert sind. 71 | 72 | ## Nächste Schritte 73 | 74 | In diesem Beispiel werden die Grundlagen für das Funktionieren Ihrer Apps mit Microsoft Graph gezeigt. Mithilfe von Office 365-APIs können Ihre Apps viele weitere Aktionen vornehmen, z. B. das Unterstützen Ihrer Benutzer bei der Verwaltung ihrer täglichen Arbeit mit dem Kalender, das Auffinden der benötigten Informationen in allen in OneDrive gespeicherten Dateien oder das Auffinden der gewünschten Person in ihrer Liste der Kontakte. Im [Codeausschnitt-Beispiel für Android](../../../android-java-snippets-sample) warten wir noch weitere interessante Dinge für Sie. 75 | 76 | ## Zusätzliche Ressourcen 77 | 78 | * [Erste Schritte mit Office 365-APIs, unterstützt von Microsoft Graph](http://dev.office.com/getting-started/office365apis) 79 | * [Microsoft Graph-Übersicht](http://graph.microsoft.io) 80 | * [Microsoft Graph-SDK für Android](../../../msgraph-sdk-android) 81 | * [Codeausschnittbeispiel für Android](../../../android-java-snippets-sample) 82 | 83 | ## Copyright 84 | Copyright (c) 2016 Microsoft. Alle Rechte vorbehalten. 85 | -------------------------------------------------------------------------------- /README-Localized/README-es-es.md: -------------------------------------------------------------------------------- 1 | # Ejemplo de Connect para Android con SDK de Microsoft Graph 2 | 3 | 4 | >**Nota**: Estamos actualizando este ejemplo para poder usarlo con la [biblioteca de autenticación recomendada](https://docs.microsoft.com/es-es/azure/active-directory/develop/active-directory-v2-libraries#compatible-client-libraries) para las aplicaciones de Android. 5 | 6 | 7 | > **¿Desea compilar aplicaciones para clientes empresariales?** Es posible que la aplicación no funcione si su cliente empresarial activa características de seguridad de movilidad empresarial como el acceso condicional al dispositivo. En casos así, es posible que no tenga constancia de esta activación y que sus clientes obtengan errores. 8 | 9 | > Para ser compatible con **todos los clientes empresariales** en **todos los escenarios de empresa**, tiene que usar el punto de conexión de AD de Azure y administrar las aplicaciones mediante el [Portal de administración de Azure](https://aka.ms/aadapplist). Para obtener más información, consulte [Decidir entre los puntos de conexión de Azure AD y Azure AD v2.0 ](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint). 10 | 11 | [![Ejemplo de Connect para Microsoft Graph](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "Haga clic para ver el ejemplo en acción"). 12 | 13 | Conectarse a Microsoft Graph es el primer paso que tiene que realizar cada aplicación Android para empezar a trabajar con los datos y servicios de Office 365. Este ejemplo muestra cómo conectar y cómo llamar después a una API a través del SDK de Microsoft Graph. 14 | 15 | ## Requisitos del dispositivo 16 | 17 | Para ejecutar el ejemplo Connect, el dispositivo debe cumplir los siguientes requisitos: 18 | 19 | * Una pantalla de tamaño de 800 x 480 o superior. 20 | * Nivel de API de Android 16 o superior. 21 | 22 | ## Requisitos previos 23 | 24 | Para usar el ejemplo Connect de Android, necesita lo siguiente: 25 | 26 | * Versión 1.0 de [Android Studio](http://developer.android.com/sdk/index.html) o superior. 27 | * [Kit de desarrollo Java (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html). 28 | 29 | 30 | ##Registrar y configurar la aplicación 31 | 32 | 1. Inicie sesión en el [Portal de registro de la aplicación](https://apps.dev.microsoft.com/) mediante su cuenta personal, profesional o educativa. 33 | 2. Seleccione **Agregar una aplicación**. 34 | 3. Escriba un nombre para la aplicación y seleccione **Crear aplicación**. 35 | 36 | Se muestra la página de registro, indicando las propiedades de la aplicación. 37 | 38 | 4. En **Plataformas**, seleccione **Agregar plataforma**. 39 | 5. Seleccione **Aplicación móvil**. 40 | 6. Copie el **identificador de la aplicación**, ya que lo necesitará en la sección siguiente. 41 | 7. Haga clic en **Guardar**. 42 | 43 | ## Abrir el ejemplo con Android Studio 44 | 45 | 1. Instale [Android Studio](http://developer.android.com/sdk/index.html) y agregue los paquetes del SDK de Android según las [instrucciones](http://developer.android.com/sdk/installing/adding-packages.html) de developer.android.com. 46 | 2. Descargue o clone este ejemplo. 47 | 3. Inicie Android Studio. 48 | 1. Cierre todos los proyectos que tenga abiertos y, después, elija **Abrir un proyecto existente de Android Studio**. 49 | 2. Examine su repositorio local y elija el proyecto Android-Connect. Haga clic en **Aceptar**. 50 | 51 | > Nota: Android Studio muestra una notificación **Marcos de trabajo detectados** si no tiene instalado el **repositorio de soporte de Android**. Abra el administrador de SDK y agregue el repositorio de soporte de Android para evitar la notificación Marcos de trabajo detectados. 52 | 4. Abra el archivo Constants.java. 53 | * Reemplace *ENTER_YOUR_CLIENT_ID* con el identificador de la aplicación de la sección anterior. 54 | 55 | Una vez creado el ejemplo Connect, puede ejecutarlo en un emulador o en un dispositivo. Elija un dispositivo con un nivel de API 16 o superior desde el cuadro de diálogo **Elegir dispositivo**. 56 | 57 | Para obtener más información acerca del ejemplo, consulte [Llamar a Microsoft Graph en una aplicación Android](https://graph.microsoft.io/en-us/docs/platform/android). 58 | 59 | 60 | ## Colaboradores ## 61 | 62 | Si le gustaría contribuir a este ejemplo, consulte [CONTRIBUTING.MD](/CONTRIBUTING.md). 63 | 64 | Este proyecto ha adoptado el [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) (Código de conducta de código abierto de Microsoft). Para obtener más información, consulte las [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) (Preguntas más frecuentes del código de conducta) o póngase en contacto con [opencode@microsoft.com](mailto:opencode@microsoft.com) con otras preguntas o comentarios. 65 | 66 | ## Preguntas y comentarios 67 | 68 | Nos encantaría recibir sus comentarios acerca del ejemplo Connect. Puede enviarnos sus preguntas y sugerencias a través de la sección [Problemas](issues) de este repositorio. 69 | 70 | Las preguntas generales sobre el desarrollo de Microsoft Graph deben publicarse en [Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API). Asegúrese de que sus preguntas o comentarios se etiquetan con y [MicrosoftGraph] y [API]. 71 | 72 | ## Pasos siguientes 73 | 74 | Este ejemplo muestra solo los elementos esenciales que las aplicaciones necesitan para funcionar en Microsoft Graph. Sus aplicaciones pueden hacer muchas más cosas con las API de Office 365, como ayudar a sus usuarios a administrar su día de trabajo con el calendario, encontrar la información que necesitan en todos los archivos que almacenan en OneDrive o encontrar la persona exacta que necesitan de la lista de contactos. Disponemos de más información para compartir con usted en el [Ejemplo de fragmentos de código para Android](../../../android-java-snippets-sample). 75 | 76 | ## Recursos adicionales 77 | 78 | * [Empiece a trabajar con la API de Office 365 con tecnología de Microsoft Graph](http://dev.office.com/getting-started/office365apis) 79 | * [Información general de Microsoft Graph](http://graph.microsoft.io) 80 | * [SDK de Microsoft Graph para Android](../../../msgraph-sdk-android) 81 | * [Ejemplo de fragmentos de código para Android](../../../android-java-snippets-sample) 82 | 83 | ## Copyright 84 | Copyright (c) 2016 Microsoft. Todos los derechos reservados. 85 | -------------------------------------------------------------------------------- /README-Localized/README-fr-fr.md: -------------------------------------------------------------------------------- 1 | # Exemple de connexion d’Android à l’aide du kit de développement Microsoft Graph 2 | 3 | 4 | >**Remarque :** nous sommes en train de mettre à jour cet exemple pour utiliser la [bibliothèque d’authentification recommandée](https://docs.microsoft.com/fr-fr/azure/active-directory/develop/active-directory-v2-libraries#compatible-client-libraries) pour les applications Android. 5 | 6 | 7 | > **Vous voulez créer des applications pour des entreprises ?** Il est possible que votre application ne fonctionne pas si l’entreprise a activé les fonctionnalités de sécurité pour la mobilité en entreprise comme l’accès conditionnel des appareils. Dans ce cas, vos clients peuvent rencontrer des erreurs. 8 | 9 | > Pour prendre en charge **toutes les entreprises clientes** dans **tous les scénarios**, utilisez le point de terminaison Azure AD et gérez vos applications avec le [portail de gestion Azure](https://aka.ms/aadapplist). Pour plus d’informations, consultez les [fonctionnalités des points de terminaison Azure AD et Azure AD v2.0](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint). 10 | 11 | [![Exemple de connexion Microsoft Graph](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "Cliquez ici pour voir l’exemple en action") 12 | 13 | Chaque application Android commence par se connecter à Microsoft Graph pour travailler avec les services et les données Office 365. Cet exemple explique comment connecter, puis appeler une API via le kit de développement Microsoft Graph. 14 | 15 | ## Configuration requise de l’appareil 16 | 17 | Pour exécuter l’exemple de connexion, votre appareil doit respecter les exigences suivantes : 18 | 19 | * Un écran de 800 x 480, ou plus. 20 | * Une API Android de niveau 16, ou supérieur. 21 | 22 | ## Conditions préalables 23 | 24 | Pour utiliser l’exemple de connexion d’Android, vous devez disposer des éléments suivants : 25 | 26 | * [Android Studio](http://developer.android.com/sdk/index.html) version 1.0 ou ultérieure. 27 | * [Kit de développement Java (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html). 28 | 29 | 30 | ##Enregistrement et configuration de l’application 31 | 32 | 1. Connectez-vous au [portail d’inscription des applications](https://apps.dev.microsoft.com/) en utilisant votre compte personnel, professionnel ou scolaire. 33 | 2. Sélectionnez **Ajouter une application**. 34 | 3. Entrez un nom pour l’application, puis sélectionnez **Créer une application**. 35 | 36 | La page d’inscription s’affiche, répertoriant les propriétés de votre application. 37 | 38 | 4. Sous **Plateformes**, sélectionnez **Ajouter une plateforme**. 39 | 5. Sélectionnez **Application mobile**. 40 | 6. Copiez l’**ID de l’application**. Vous en aurez besoin dans la section suivante. 41 | 7. Cliquez sur **Enregistrer**. 42 | 43 | ## Ouverture de l’exemple à l’aide d’Android Studio 44 | 45 | 1. Installez [Android Studio](http://developer.android.com/sdk/index.html) et ajoutez le kit de développement logiciel Android conformément aux [instructions](http://developer.android.com/sdk/installing/adding-packages.html) indiquées sur developer.android.com. 46 | 2. Téléchargez ou clonez cet exemple. 47 | 3. Démarrez Android Studio. 48 | 1. Fermez tous les projets ouverts, puis cliquez sur **Ouvrir un projet Android Studio existant**. 49 | 2. Ouvrez votre référentiel local et sélectionnez le projet Android-Connect. Cliquez sur **OK**. 50 | 51 | > Remarque : Android Studio affiche une notification **Infrastructures détectées** si vous n’avez pas installé le **référentiel de support Android**. Ouvrez le Gestionnaire de kit de développement logiciel (SDK) et ajoutez le référentiel de support Android afin d’éviter la notification Infrastructures détectées. 52 | 4. Ouvrez le fichier Constants.java. 53 | * Remplacez *ENTER_YOUR_CLIENT_ID* par l’ID de l’application copiée précédemment. 54 | 55 | Une fois l’exemple de connexion créé, vous pouvez l’exécuter sur un émulateur ou un appareil. Choisissez un appareil avec une API de niveau 16 ou supérieur dans la boîte de dialogue **Choisir un appareil**. 56 | 57 | Pour en savoir plus sur cet exemple, consultez la rubrique relative à l’[appel de Microsoft Graph dans une application Android](https://graph.microsoft.io/en-us/docs/platform/android). 58 | 59 | 60 | ## Contribution ## 61 | 62 | Si vous souhaitez contribuer à cet exemple, voir [CONTRIBUTING.MD](/CONTRIBUTING.md). 63 | 64 | Ce projet a adopté le [code de conduite Microsoft Open Source](https://opensource.microsoft.com/codeofconduct/). Pour plus d’informations, reportez-vous à la [FAQ relative au code de conduite](https://opensource.microsoft.com/codeofconduct/faq/) ou contactez [opencode@microsoft.com](mailto:opencode@microsoft.com) pour toute question ou tout commentaire. 65 | 66 | ## Questions et commentaires 67 | 68 | Nous serions ravis de connaître votre opinion sur l’exemple de connexion. Vous pouvez nous faire part de vos questions et suggestions dans la rubrique [Problèmes](issues) de ce référentiel. 69 | 70 | Les questions générales sur le développement de Microsoft Graph doivent être publiées sur [Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API). Veillez à poser vos questions ou à rédiger vos commentaires en utilisant les tags [MicrosoftGraph] et [API]. 71 | 72 | ## Étapes suivantes 73 | 74 | Cet exemple montre uniquement les conditions minimales que vos applications doivent remplir pour fonctionner avec Microsoft Graph. Vos applications peuvent faire tellement de choses grâce aux API Office 365 : aider vos utilisateurs à organiser leur semaine avec le calendrier, rechercher les informations dont ils ont besoin dans tous les fichiers stockés dans OneDrive ou rechercher la bonne personne dans leur liste de contacts. Nous avons bien d’autres choses à vous proposer dans l’[exemple d’extraits de code pour Android](../../../android-java-snippets-sample). 75 | 76 | ## Ressources supplémentaires 77 | 78 | * [Prise en main des API Office 365 fournies par Microsoft Graph](http://dev.office.com/getting-started/office365apis) 79 | * [Présentation de Microsoft Graph](http://graph.microsoft.io) 80 | * [Kit de développement logiciel (SDK) Microsoft Graph pour Android](../../../msgraph-sdk-android) 81 | * [Exemple d’extraits de code pour Android](../../../android-java-snippets-sample) 82 | 83 | ## Copyright 84 | Copyright (c) 2016 Microsoft. Tous droits réservés. 85 | -------------------------------------------------------------------------------- /README-Localized/README-ja-jp.md: -------------------------------------------------------------------------------- 1 | # Microsoft Graph SDK を使用した Android 用 Connect サンプル 2 | 3 | 4 | >**注:**Android アプリ向けの[推奨される認証ライブラリ](https://docs.microsoft.com/ja-jp/azure/active-directory/develop/active-directory-v2-libraries#compatible-client-libraries)を使用するこのサンプルは、現在更新中です。 5 | 6 | 7 | > **エンタープライズのお客様向けにアプリを作成していますか?**エンタープライズのお客様が、条件付きのデバイスへのアクセスのようなエンタープライズ モビリティ セキュリティの機能をオンにしている場合、アプリが動作しない可能性があります。その場合、気がつかないまま、お客様の側でエラーが発生してしまう可能性があります。 8 | 9 | > **すべてのエンタープライズのお客様**の**すべてのエンタープライズ シナリオ**をサポートするには、Azure AD のエンドポイントを使用し、[Azure の管理ポータル](https://aka.ms/aadapplist)でアプリを管理する必要があります。詳細については、「[Azure AD か Azure AD v2.0 エンドポイントかを決定する](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint)」を参照してください。 10 | 11 | [![Microsoft Graph Connect のサンプル](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "稼働中のサンプルを確認するにはこちらをクリックしてください") 12 | 13 | 各 Android アプリで Office 365 のサービスとデータの操作を開始するため、最初に Microsoft Graph に接続する必要があります。このサンプルでは、Microsoft Graph SDK 経由で、1 つの API に接続して呼び出す方法を示します。 14 | 15 | ## デバイスの要件 16 | 17 | Connect のサンプルを実行するには、デバイスが次の要件を満たしている必要があります。 18 | 19 | * 画面のサイズが 800 x 480 以上である。 20 | * Android の API レベルが 16 以上である。 21 | 22 | ## 前提条件 23 | 24 | Android 用 Connect のサンプルを使用するには以下が必要です: 25 | 26 | * [Android Studio](http://developer.android.com/sdk/index.html) バージョン 1.0 以上。 27 | * [Java 開発キット (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html)。 28 | 29 | 30 | ##アプリを登録して構成する 31 | 32 | 1. 個人用アカウント、あるいは職場または学校アカウントのいずれかを使用して、[アプリ登録ポータル](https://apps.dev.microsoft.com/)にサインインします。 33 | 2. **[アプリの追加]** を選択します。 34 | 3. アプリの名前を入力して、**[アプリケーションの作成]** を選択します。 35 | 36 | 登録ページが表示され、アプリのプロパティが一覧表示されます。 37 | 38 | 4. **[プラットフォーム]** で、**[プラットフォームの追加]** を選択します。 39 | 5. **[モバイル アプリケーション]** を選択します。 40 | 6. 次のセクションで必要になるので、**アプリケーション ID** をコピーしておきます。 41 | 7. **[保存]** をクリックします。 42 | 43 | ## Android Studio を使用してサンプルを開く 44 | 45 | 1. developer.android.com の[指示](http://developer.android.com/sdk/index.html)に従って、[Android Studio](http://developer.android.com/sdk/installing/adding-packages.html) をインストールし、Android SDK パッケージを追加します。 46 | 2. このサンプルをダウンロードするか、クローンを作成します。 47 | 3. Android Studio を起動します。 48 | 1. 開いているプロジェクトをすべて閉じ、**[既存のAndroid Studio プロジェクトを開く]** を選択します。 49 | 2. ローカル リポジトリを参照し、Android-Connect プロジェクトを選択します。**[OK]** をクリックします。 50 | 51 | > 注:**Android サポート リポジトリ**がインストールされていない場合、Android Studio は**フレームワーク検出**の通知を表示します。フレームワーク検出の通知が表示されないようにするには、SDK マネージャーを開き、Android サポート リポジトリを追加してください。 52 | 4. Constants.java ファイルを開きます。 53 | * *ENTER_YOUR_CLIENT_ID* を前のセクションのアプリケーション ID と置き換えます。 54 | 55 | Connect のサンプルをビルドしたら、エミュレーターまたはデバイス上で実行できます。**[デバイスの選択]** ダイアログから API レベル 16 以上のデバイスを選びます。 56 | 57 | サンプルについて詳細については、「[Android アプリで Microsoft Graph を呼び出す](https://graph.microsoft.io/ja-jp/docs/platform/android)」を参照してください。 58 | 59 | 60 | ## 投稿 ## 61 | 62 | このサンプルに投稿する場合は、[CONTRIBUTING.MD](/CONTRIBUTING.md) を参照してください。 63 | 64 | このプロジェクトでは、[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) が採用されています。詳細については、「[規範に関する FAQ](https://opensource.microsoft.com/codeofconduct/faq/)」を参照してください。または、その他の質問やコメントがあれば、[opencode@microsoft.com](mailto:opencode@microsoft.com) までにお問い合わせください。 65 | 66 | ## 質問とコメント 67 | 68 | Connect のサンプルに関するフィードバックをお寄せください。質問や提案につきましては、このリポジトリの「[問題](issues)」セクションで送信できます。 69 | 70 | Microsoft Graph 開発全般の質問につきましては、「[Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API)」に投稿してください。質問やコメントには、必ず [MicrosoftGraph] と [API] のタグを付けてください。 71 | 72 | ## 次の手順 73 | 74 | このサンプルでは、アプリが Microsoft Graph を使用して操作する必要がある重要項目のみを示しています。Office 365 API を使って、アプリでできることはさらにあります。たとえば、ユーザーが予定表で作業日を管理できるようにする、ユーザーが OneDrive に保存したすべてのファイルから必要な情報を検索する、連絡先のリストからユーザーが必要とする人を正確に見つけるなどです。「[Android 用スニペットのサンプル](../../../android-java-snippets-sample)」で、さらに説明しています。 75 | 76 | ## 追加リソース 77 | 78 | * [Microsoft Graph が提供する Office 365 API の使用を開始する](http://dev.office.com/getting-started/office365apis) 79 | * [Microsoft Graph の概要](http://graph.microsoft.io) 80 | * [Android 用Microsoft Graph SDK](../../../msgraph-sdk-android) 81 | * [Android 用スニペット サンプル](../../../android-java-snippets-sample) 82 | 83 | ## 著作権 84 | Copyright (c) 2016 Microsoft. All rights reserved. 85 | -------------------------------------------------------------------------------- /README-Localized/README-pt-br.md: -------------------------------------------------------------------------------- 1 | # Exemplo de conexão para Android usando o SDK do Microsoft Graph 2 | 3 | 4 | >**Observação:** estamos atualizando este exemplo para usar a [biblioteca de autenticação recomendada](https://docs.microsoft.com/pt-br/azure/active-directory/develop/active-directory-v2-libraries#compatible-client-libraries) para aplicativos para Android. 5 | 6 | 7 | > **Criando aplicativos para clientes corporativos?** O aplicativo pode não funcionar caso o cliente corporativo habilite os recursos Enterprise Mobility + Security, como acesso condicional ao dispositivo. Nesse caso, pode ser que você não esteja ciente e seu cliente pode enfrentar problemas de erro. 8 | 9 | > Para fornecer suporte a **todos os clientes corporativos**, em **todos os cenários corporativos**, use o ponto de extremidade do Microsoft Azure AD e gerencie os aplicativos usando o [Portal de Gerenciamento do Microsoft Azure](https://aka.ms/aadapplist). Para saber mais, confira o tópico [Decidindo entre os pontos de extremidade do Microsoft Azure AD e do Microsoft Azure AD versão 2.0](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint). 10 | 11 | [![Exemplo de conexão usando o Microsoft Graph](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "Clique no exemplo para vê-lo em ação") 12 | 13 | Conectar-se ao Microsoft Graph é a primeira etapa para que os aplicativos Android comecem a funcionar com dados e serviços do Office 365. Este exemplo mostra como conectar e chamar uma única API através do SDK do Microsoft Graph. 14 | 15 | ## Requisitos do dispositivo 16 | 17 | Para executar o exemplo de conexão, o dispositivo deve atender aos seguintes requisitos: 18 | 19 | * Uma tela de tamanho 800 x 480 ou maior. 20 | * API Android nível 16 ou superior. 21 | 22 | ## Pré-requisitos 23 | 24 | Para usar o exemplo de conexão para Android, é necessário o seguinte: 25 | 26 | * [Android Studio](http://developer.android.com/sdk/index.html) versão 1.0 ou posterior. 27 | * [JDK (Java Development Kit) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html). 28 | 29 | 30 | ##Registrar e configurar o aplicativo 31 | 32 | 1. Entre no [Portal de Registro do Aplicativo](https://apps.dev.microsoft.com/) usando sua conta pessoal ou sua conta comercial ou escolar. 33 | 2. Selecione **Adicionar um aplicativo**. 34 | 3. Insira um nome para o aplicativo e selecione **Criar aplicativo**. 35 | 36 | A página de registro é exibida, listando as propriedades do seu aplicativo. 37 | 38 | 4. Em **Plataformas**, selecione **Adicionar plataforma**. 39 | 5. Escolha **Aplicativo móvel**. 40 | 6. Copie a **ID do Aplicativo**, pois você vai precisar dela na seção seguinte. 41 | 7. Clique em **Salvar**. 42 | 43 | ## Abra o exemplo usando o Android Studio 44 | 45 | 1. Instale o [Android Studio](http://developer.android.com/sdk/index.html) e adicione os pacotes do SDK do Android de acordo com as [instruções](http://developer.android.com/sdk/installing/adding-packages.html) na página developer.android.com. 46 | 2. Baixe ou clone esse exemplo. 47 | 3. Inicie o Android Studio. 48 | 1. Feche todos os projetos abertos e escolha **Abrir um projeto existente do Android Studio**. 49 | 2. Navegue até o repositório local e escolha o projeto Android-Connect. Clique em **OK**. 50 | 51 | > Observação: O Android Studio mostra uma notificação de **Estruturas detectadas** se você não tiver o **Repositório de Suporte do Android** instalado. Abra o gerenciador de SDK e adicione o Repositório de Suporte do Android para evitar a notificação de estruturas detectadas. 52 | 4. Abra o arquivo Constants.java. 53 | * Substitua o texto *INSERIR_ID_DO_CLIENTE* pela ID do Aplicativo que você copiou na seção anterior. 54 | 55 | Depois de criar o exemplo de conexão, você pode executá-lo em um emulador ou dispositivo. Escolha um dispositivo com API de nível 16 ou superior na caixa de diálogo **Escolher dispositivo**. 56 | 57 | Para saber mais sobre o exemplo, confira o artigo [Chamar o Microsoft Graph em um aplicativo Android](https://graph.microsoft.io/en-us/docs/platform/android). 58 | 59 | 60 | ## Colaboração ## 61 | 62 | Se quiser contribuir para esse exemplo, confira [CONTRIBUTING.MD](/CONTRIBUTING.md). 63 | 64 | Este projeto adotou o [Código de Conduta do Código Aberto da Microsoft](https://opensource.microsoft.com/codeofconduct/). Para saber mais, confira as [Perguntas frequentes do Código de Conduta](https://opensource.microsoft.com/codeofconduct/faq/) ou contate [opencode@microsoft.com](mailto:opencode@microsoft.com) se tiver outras dúvidas ou comentários. 65 | 66 | ## Perguntas e comentários 67 | 68 | Gostaríamos de saber sua opinião sobre o exemplo de conexão. Você pode nos enviar suas perguntas e sugestões por meio da seção [Issues](issues) deste repositório. 69 | 70 | As perguntas sobre o desenvolvimento do Microsoft Graph em geral devem ser postadas no [Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API). Não deixe de marcar as perguntas ou comentários com [MicrosoftGraph] e [API]. 71 | 72 | ## Próximas etapas 73 | 74 | Este exemplo mostra apenas os conceitos básicos necessários para que os aplicativos funcionem com o Microsoft Graph. O aplicativo pode fazer muito mais usando as APIs do Office 365, como ajudar os usuários a gerenciar os dias úteis com o calendário, localizar apenas as informações necessárias em todos os arquivos armazenados no OneDrive ou localizar uma pessoa específica na lista de contatos. Temos mais recursos para compartilhar com você no [Exemplo de trechos de código para Android](../../../android-java-snippets-sample). 75 | 76 | ## Recursos adicionais 77 | 78 | * [Começar a usar as APIs do Office 365 da plataforma Microsoft Graph](http://dev.office.com/getting-started/office365apis) 79 | * [Visão geral do Microsoft Graph](http://graph.microsoft.io) 80 | * [SDK do Microsoft Graph para Android](../../../msgraph-sdk-android) 81 | * [Exemplo de trechos de código para Android](../../../android-java-snippets-sample) 82 | 83 | ## Direitos autorais 84 | Copyright © 2016 Microsoft. Todos os direitos reservados. 85 | -------------------------------------------------------------------------------- /README-Localized/README-ru-ru.md: -------------------------------------------------------------------------------- 1 | # Приложение Connect для Android, использующее Microsoft Graph SDK 2 | 3 | 4 | >**Примечание.** Мы работаем над обновлением этого примера и добавлением в него [рекомендованной библиотеки проверки подлинности](https://docs.microsoft.com/ru-ru/azure/active-directory/develop/active-directory-v2-libraries#compatible-client-libraries) для приложений для Android. 5 | 6 | 7 | > **Создаете приложения для корпоративных клиентов?** Ваше приложение может не работать, если корпоративный клиент включит функции корпоративной безопасности для мобильных устройств, например условный доступ с устройств. В этом случае у пользователей могут возникать ошибки, а вы не будете об этом знать. 8 | 9 | > Для поддержки **всех корпоративных клиентов** в **любых корпоративных сценариях** необходимо использовать конечную точку Azure AD и управлять приложениями с помощью [портала управления Azure](https://aka.ms/aadapplist). Дополнительные сведения см. в разделе [Выбор между конечными точками Azure AD и Azure AD версии 2.0](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint). 10 | 11 | [![Пример Microsoft Graph Connect.](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "Щелкните, чтобы просмотреть пример в действии") 12 | 13 | Чтобы начать работу со службами и данными Office 365, приложение для Android должно подключиться к Microsoft Graph. В этом примере показано, как подключиться, а затем вызвать один API через пакет SDK Microsoft Graph. 14 | 15 | ## Требования к устройству 16 | 17 | Для запуска приложения для подключения устройство должно соответствовать следующим требованиям: 18 | 19 | * размер экрана должен составлять не менее 800 x 480; 20 | * должен использоваться API Android 16 или более высокого уровня. 21 | 22 | ## Необходимые компоненты 23 | 24 | Для работы с приложением Connect для Android необходимы следующие компоненты: 25 | 26 | * [Android Studio](http://developer.android.com/sdk/index.html) 1.0 или более поздней версии. 27 | * [Java Development Kit (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html). 28 | 29 | 30 | ##Регистрация и настройка приложения 31 | 32 | 1. Войдите на [портал регистрации приложений](https://apps.dev.microsoft.com/) с помощью личной, рабочей или учебной учетной записи. 33 | 2. Выберите пункт **Добавить приложение**. 34 | 3. Введите имя приложения и выберите пункт **Создать приложение**. 35 | 36 | Откроется страница регистрации со свойствами приложения. 37 | 38 | 4. В разделе **Платформы** выберите пункт **Добавление платформы**. 39 | 5. Выберите пункт **Мобильное приложение**. 40 | 6. Скопируйте **код приложения**, он понадобится вам при работе со следующим разделом. 41 | 7. Нажмите кнопку **Сохранить**. 42 | 43 | ## Открытие примера с помощью Android Studio 44 | 45 | 1. Установите [Android Studio](http://developer.android.com/sdk/index.html) и добавьте пакеты SDK для Android в соответствии с [инструкциями](http://developer.android.com/sdk/installing/adding-packages.html) на сайте developer.android.com. 46 | 2. Скачайте или клонируйте этот пример. 47 | 3. Запустите Android Studio. 48 | 1. Закройте все открытые проекты, а затем выберите команду **Open an existing Android Studio project** (Открыть существующий проект Android Studio). 49 | 2. Откройте локальный репозиторий и выберите проект Android-Connect. Нажмите кнопку **ОК**. 50 | 51 | > Примечание. Если у вас не установлен пакет **Android Support Repository**Android Studio покажет уведомление **Frameworks detected**. Чтобы избежать этого, откройте диспетчер SDK и добавьте пакет Android Support Repository. 52 | 4. Откройте файл Constants.java. 53 | * Вместо фразы *ВВЕДИТЕ_ИДЕНТИФИКАТОР_КЛИЕНТА* вставьте код приложения, который вы сохранили в предыдущем разделе. 54 | 55 | После сборки пример подключения можно запустить в эмуляторе или на устройстве. Выберите устройство с API 16 или более высокого уровня в диалоговом окне **Choose device** (Выбор устройства). 56 | 57 | Дополнительные сведения о примере см. в статье [Вызов Microsoft Graph в приложении для Android](https://graph.microsoft.io/en-us/docs/platform/android). 58 | 59 | 60 | ## Добавление кода ## 61 | 62 | Если вы хотите добавить код в этот пример, просмотрите статью [CONTRIBUTING.MD](/CONTRIBUTING.md). 63 | 64 | Этот проект соответствует [правилам поведения Майкрософт, касающимся обращения с открытым кодом](https://opensource.microsoft.com/codeofconduct/). Читайте дополнительные сведения в [разделе вопросов и ответов по правилам поведения](https://opensource.microsoft.com/codeofconduct/faq/) или отправляйте новые вопросы и замечания по адресу [opencode@microsoft.com](mailto:opencode@microsoft.com). 65 | 66 | ## Вопросы и комментарии 67 | 68 | Мы будем рады узнать ваше мнение о примере Connect. Перейдите на вкладку [Issues](issues) (Проблемы) этого репозитория, чтобы задать нам вопрос или отправить свои предложения. 69 | 70 | Общие вопросы о разработке решений для Microsoft Graph следует задавать на сайте [Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API). Обязательно помечайте свои вопросы и комментарии тегами [MicrosoftGraph] или [API]. 71 | 72 | ## Дальнейшие действия 73 | 74 | В этом примере показаны только основные компоненты, необходимые приложениям для работы с Microsoft Graph. Интерфейсы API Office 365 значительно расширяют возможности ваших приложений. Например, пользователи могут управлять расписанием своего рабочего дня с помощью календаря, находить во всех файлах из OneDrive только нужные сведения, а также искать необходимых пользователей в своих списках контактов. Узнать больше можно из [примера фрагментов кода для Android](../../../android-java-snippets-sample). 75 | 76 | ## Дополнительные ресурсы 77 | 78 | * [Начало работы с интерфейсами API Office 365 на платформе Microsoft Graph](http://dev.office.com/getting-started/office365apis) 79 | * [Общие сведения о Microsoft Graph](http://graph.microsoft.io) 80 | * [Пакет SDK Microsoft Graph для Android](../../../msgraph-sdk-android) 81 | * [Примеры фрагментов кода для Android](../../../android-java-snippets-sample) 82 | 83 | ## Авторское право 84 | (c) Корпорация Майкрософт (Microsoft Corporation), 2016. Все права защищены. 85 | -------------------------------------------------------------------------------- /README-Localized/README-zh-cn.md: -------------------------------------------------------------------------------- 1 | # 使用 Microsoft Graph SDK 的适用于 Android 的 Connect 示例 2 | 3 | 4 | >**注意:**我们正在更新此示例以使用适用于 Android 应用的[推荐身份验证库](https://docs.microsoft.com/zh-cn/azure/active-directory/develop/active-directory-v2-libraries#compatible-client-libraries)。 5 | 6 | 7 | > **为企业客户生成应用?**如果企业客户启用企业移动性安全功能,如条件性设备访问,应用可能无法运行。在这种情况下,你可能不知道,而且客户可能会遇到错误。 8 | 9 | > 若要在**所有企业方案**中支持**所有企业客户**,必须使用 Azure AD 终结点并使用 [Azure 管理门户](https://aka.ms/aadapplist)管理应用。有关详细信息,请参阅[在 Azure AD 和 Azure AD v2.0 终结点之间做选择](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint)。 10 | 11 | [![Microsoft Graph Connect 示例](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "单击查看使用中的示例") 12 | 13 | 连接到 Microsoft Graph 是每个 Android 应用开始使用 Office 365 服务和数据必须执行的第一步。该示例演示如何通过 Microsoft Graph SDK 连接并调用一个 API。 14 | 15 | ## 设备要求 16 | 17 | 要运行该 Connect 示例,您的设备需要满足以下要求: 18 | 19 | * 800 x 480 或更大的屏幕尺寸。 20 | * Android API 级别为 16 级或更高。 21 | 22 | ## 先决条件 23 | 24 | 若要使用适于 Android 的 Connect 示例,你需要以下各项: 25 | 26 | * [Android Studio](http://developer.android.com/sdk/index.html) 版本 1.0 或更高。 27 | * [Java 开发工具包 (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html)。 28 | 29 | 30 | ##注册和配置应用 31 | 32 | 1. 使用个人或工作或学校帐户登录到 [应用注册门户](https://apps.dev.microsoft.com/)。 33 | 2. 选择“**添加应用**”。 34 | 3. 为应用输入名称,并选择“**创建应用程序**”。 35 | 36 | 将显示注册页,其中列出应用的属性。 37 | 38 | 4. 在“**平台**”下,选择“**添加平台**”。 39 | 5. 选择“**移动应用程序**”。 40 | 6. 复制在下一节中需要使用的**应用程序 ID**。 41 | 7. 单击“**保存**”。 42 | 43 | ## 打开使用 Android Studio 的示例 44 | 45 | 1. 安装 [Android Studio](http://developer.android.com/sdk/index.html) 并根据 developer.android.com 上的[说明](http://developer.android.com/sdk/installing/adding-packages.html) 添加 Android SDK 包。 46 | 2. 下载或克隆该示例。 47 | 3. 启动 Android Studio。 48 | 1. 关闭可能打开的任何项目,然后选择“**打开一个现有的 Android Studio 项目**”。 49 | 2. 浏览你的本地存储库,然后选择 Android-Connect 项目。单击“**确定**”。 50 | 51 | > 注意:如果你没有安装 **Android 支持存储库**,则 Android Studio 显示“**已检测到框架**”通知。打开 SDK 管理器并添加 Android 支持存储库以避免已检测到框架的通知。 52 | 4. 打开 Constants.java 文件。 53 | * 将 *ENTER_YOUR_CLIENT_ID* 替换为上一节中的应用程序 ID。 54 | 55 | 生成 Connect 示例后,可以在仿真器或设备中运行。在“**选择设备**”对话中选择配备了 API 级别为 16 级或更高级别的设备。 56 | 57 | 要了解有关该示例的详细信息,请参阅[在 Android 应用中调用 Microsoft Graph](https://graph.microsoft.io/zh-cn/docs/platform/android)。 58 | 59 | 60 | ## 参与 ## 61 | 62 | 如果想要参与本示例,请参阅 [CONTRIBUTING.MD](/CONTRIBUTING.md)。 63 | 64 | 此项目采用 [Microsoft 开源行为准则](https://opensource.microsoft.com/codeofconduct/)。有关详细信息,请参阅 [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)(行为准则常见问题解答),有任何其他问题或意见,也可联系 [opencode@microsoft.com](mailto:opencode@microsoft.com)。 65 | 66 | ## 问题和意见 67 | 68 | 我们乐意倾听你有关 Connect 示例的反馈。可以在该存储库中的[问题](issues)部分将问题和建议发送给我们。 69 | 70 | 与 Microsoft Graph 开发相关的一般问题应发布到 [Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API)。请确保你的问题或意见标记有 [MicrosoftGraph] 和 [API]。 71 | 72 | ## 后续步骤 73 | 74 | 该示例只显示应用要使用 Microsoft Graph 所需的必要条件。应用可以使用 Office 365 API 实现的功能非常之多,例如,帮助用户使用日历管理工作日,在存储于 OneDrive 中的所有文件中查找用户需要的信息,或在他们的联系人列表中找出他们需要的人员。在[适用于 Android 的代码段示例](../../../android-java-snippets-sample)方面,我们还想与你分享更多的信息。 75 | 76 | ## 其他资源 77 | 78 | * [由 Microsoft Graph 提供支持的 Office 365 API 入门](http://dev.office.com/getting-started/office365apis) 79 | * [Microsoft Graph 概述](http://graph.microsoft.io) 80 | * [适用于 Android 的 Microsoft Graph SDK](../../../msgraph-sdk-android) 81 | * [适用于 Android 的代码段示例](../../../android-java-snippets-sample) 82 | 83 | ## 版权 84 | 版权所有 (c) 2016 Microsoft。保留所有权利。 85 | -------------------------------------------------------------------------------- /README-Localized/README-zh-tw.md: -------------------------------------------------------------------------------- 1 | # 使用 Microsoft Graph SDK 的 Connect 範例 (適用於 Android) 2 | 3 | 4 | >**附註:**我們正在更新此範例,以便使用 Android 應用程式的[建議驗證程式庫](https://docs.microsoft.com/zh-tw/azure/active-directory/develop/active-directory-v2-libraries#compatible-client-libraries)。 5 | 6 | 7 | > **為企業客戶建置應用程式?**如果您的企業客戶開啟企業行動安全性功能 (例如,條件式裝置存取),您的應用程式可能無法運作。在此情況中,您可能不會知道,而您的客戶可能會發生錯誤。 8 | 9 | > 若要支援包括**所有企業案例**的**所有企業客戶**,您必須使用 Azure AD 端點,並使用 [Azure 管理入口網站](https://aka.ms/aadapplist)來管理您的應用程式。如需詳細資訊,請參閱 [在 Azure AD 與 Azure AD v2.0 端點之間進行選擇](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint)。 10 | 11 | [![Microsoft Graph Connect 範例](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "按一下以查看執行中的範例") 12 | 13 | 連接到 Microsoft Graph 是每個 Android 應用程式要開始使用 Office 365 服務和資料時,必須採取的第一個步驟。此範例示範如何透過 Microsoft Graph SDK 連接而後呼叫一個 API。 14 | 15 | ## 裝置需求 16 | 17 | 若要執行 Connect 範例,您的裝置必須符合下列需求: 18 | 19 | * 800 x 480 或更大的螢幕大小。 20 | * Android API 層級 16 或更高層級。 21 | 22 | ## 必要條件 23 | 24 | 若要使用 Android 適用的 Connect 範例,您需要下列各項: 25 | 26 | * [Android Studio](http://developer.android.com/sdk/index.html) 1.0 版或更新版本。 27 | * [Java 開發套件 (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html)。 28 | 29 | 30 | ##註冊和設定應用程式 31 | 32 | 1. 使用您的個人或工作或學校帳戶登入[應用程式註冊入口網站](https://apps.dev.microsoft.com/)。 33 | 2. 選取 [新增應用程式]****。 34 | 3. 為應用程式輸入名稱,然後選取 [建立應用程式]****。 35 | 36 | [註冊] 頁面隨即顯示,列出您的應用程式的屬性。 37 | 38 | 4. 在 [平台]**** 底下,選取 [新增平台]****。 39 | 5. 選取 [行動應用程式]****。 40 | 6. 複製**應用程式識別碼**,在下一節您將會需要它。 41 | 7. 按一下 [儲存]****。 42 | 43 | ## 使用 Android Studio 開啟範例 44 | 45 | 1. 根據 developer.android.com 上的[](http://developer.android.com/sdk/installing/adding-packages.html),安裝 [Android Studio](http://developer.android.com/sdk/index.html) 及新增 Android SDK 套件。 46 | 2. 下載或複製這個範例。 47 | 3. 啟動 Android Studio。 48 | 1. 關閉您可能已開啟的任何專案,然後選擇 [開啟現有的 Android Studio 專案]****。 49 | 2. 瀏覽至您的本機存放庫,並且選擇 Android-Connect 專案。按一下 [確定]****。 50 | 51 | > 附註:如果您未安裝 **Android Support Repository**,Android Studio 會顯示 [已偵測到 Frameworks] ****開啟 SDK 管理員並加入 Android Support Repository,以避免偵測到Frameworks 的通知。 52 | 4. 開啟 Constants.java 檔案。 53 | * 將 *ENTER_YOUR_CLIENT_ID* 取代為前一節的應用程式識別碼。 54 | 55 | 一旦建置 Connect 範例,您可以在模擬器或裝置上執行它。從 [選擇裝置]**** 對話方塊挑選使用 API 層級 16 或更高層級的裝置。 56 | 57 | 若要深入了解此範例,請參閱[在 Android 應用程式中呼叫 Microsoft Graph](https://graph.microsoft.io/en-us/docs/platform/android)。 58 | 59 | 60 | ## 參與 ## 61 | 62 | 如果您想要參與這個範例,請參閱 [CONTRIBUTING.MD](/CONTRIBUTING.md)。 63 | 64 | 此專案已採用 [Microsoft 開放原始碼執行](https://opensource.microsoft.com/codeofconduct/)。如需詳細資訊,請參閱[程式碼執行常見問題集](https://opensource.microsoft.com/codeofconduct/faq/),如果有其他問題或意見,請連絡 [opencode@microsoft.com](mailto:opencode@microsoft.com)。 65 | 66 | ## 問題和建議 67 | 68 | 我們很樂於收到您對於 Connect 範例的意見反應。您可以在此儲存機制的[問題](issues)區段中,將您的問題及建議傳送給我們。 69 | 70 | 請在 [Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API) 提出有關 Microsoft Graph 開發的一般問題。務必以 [MicrosoftGraph] 和 [API] 標記您的問題或意見。 71 | 72 | ## 後續步驟 73 | 74 | 這個範例只會顯示您的應用程式要使用 Microsoft Graph 所需的基本資訊。您的應用程式可以使用 Office 365 API 做很多事,像是利用行事曆幫助您的使用者管理其工作天、在他們儲存於 OneDrive 的所有檔案中只尋找他們所需的資訊,或從他們的連絡人清單中找到她們真正需要的人。我們在[適用於 Android 的程式碼片段範例](../../../android-java-snippets-sample)有更多資訊與您分享。 75 | 76 | ## 其他資源 77 | 78 | * [開始使用 Microsoft Graph 提供的 Office 365 API](http://dev.office.com/getting-started/office365apis) 79 | * [Microsoft Graph 概觀](http://graph.microsoft.io) 80 | * [Microsoft Graph SDK for Android](../../../msgraph-sdk-android) 81 | * [Android 的程式碼片段範例](../../../android-java-snippets-sample) 82 | 83 | ## 著作權 84 | Copyright (c) 2016 Microsoft.著作權所有,並保留一切權利。 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Connect Sample for Android Using the Microsoft Graph SDK 2 | 3 | 4 | >**Note:** We've updated this sample to use the [Microsoft Authentication Library (MSAL)](https://github.com/AzureAD/microsoft-authentication-library-for-android) for Android apps. 5 | 6 | 7 | > **Building apps for enterprise customers?** Your app may not work if your enterprise customer turns on enterprise mobility security features like conditional device access. In this case, you may not know and your customers may experience errors. 8 | 9 | > To support **all enterprise customers** across **all enterprise scenarios**, you must use the Azure AD endpoint and manage your apps using the [Azure Management Portal](https://aka.ms/aadapplist). For more information, see [Deciding between the Azure AD and Azure AD v2.0 endpoints](https://graph.microsoft.io/docs/authorization/auth_overview#deciding-between-azure-ad-and-the-v2-authentication-endpoint). 10 | 11 | [![Microsoft Graph Connect sample](/readme-images/O365-Android-Connect-video_play_icon.png)](https://www.youtube.com/watch?v=3IQIDFrqhY4 "Click to see the sample in action") 12 | 13 | Connecting to Microsoft Graph is the first step every Android app must take to start working with Office 365 services and data. This sample shows how to connect and then call one API through the Microsoft Graph SDK. 14 | 15 | ## Device requirements 16 | 17 | To run the Connect sample, your device needs to meet the following requirements: 18 | 19 | * A screen size of 800 x 480 or larger. 20 | * Android API level 16 or higher. 21 | 22 | ## Prerequisites 23 | 24 | To use the Connect sample for Android, you need the following: 25 | 26 | * [Android Studio](http://developer.android.com/sdk/index.html) version 1.0 or later. 27 | * [Java Development Kit (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html). 28 | 29 | 30 | ## Register and configure the app 31 | 32 | 1. Open a browser and navigate to the [Azure Active Directory admin center](https://aad.portal.azure.com). Login using a **Work or School Account**. 33 | 34 | 1. Select **Azure Active Directory** in the left-hand navigation, then select **App registrations (Preview)** under **Manage**. 35 | 36 | ![A screenshot of the App registrations ](./readme-images/aad-portal-app-registrations.png) 37 | 38 | 1. Select **New registration**. On the **Register an application** page, set the values as follows. 39 | 40 | - Set a preferred **Name** e.g. `AndroidJavaConnect` 41 | - Set **Supported account types** to **Accounts in any organizational directory**. 42 | 43 | ![A screenshot of the Register an application page](./readme-images/aad-register-an-app.PNG) 44 | 45 | 1. Choose **Register**. On the **AndroidJavaConnect** app page, select **Overview** and copy the value of the **Application (client) ID** and save it, you will need it in the next step. 46 | 47 | ![A screenshot of Application Id](./readme-images/aad-application-id.PNG) 48 | 49 | 1. Still on the app page, select **Authentication**. Locate the section **Redirect URIs**. In the _Suggested Redirect URIs for public clients(mobile,desktop)_, check the second box so that the app can work with the MSAL libraries used in the application. (The box should contain the option _msal://auth_). Choose **Save**. 50 | 51 | ![A screenshot of Suggested Redirect URIs for Public Client](./readme-images/aad-redirect-uri-public-client.PNG) 52 | 53 | To learn about authenticating with MSAL for Android to make calls to Microsoft Graph, see [Call the Microsoft Graph API from an Android app](https://docs.microsoft.com/en-us/azure/active-directory/develop/guidedsetups/active-directory-android). 54 | 55 | 56 | ## Open the sample using Android Studio 57 | 58 | 1. Install [Android Studio](http://developer.android.com/sdk/index.html) and add the Android SDK packages according to the [instructions](http://developer.android.com/sdk/installing/adding-packages.html) on developer.android.com. 59 | 2. Download or clone this sample. 60 | 4. Start Android Studio. 61 | 1. Close any projects that you might have open, and then choose **Open an existing Android Studio project**. 62 | 2. Browse to your local repository and choose the Android-Connect project. Click **OK**. 63 | 64 | > Note: Android Studio shows a **Frameworks detected** notification if you don't have the **Android Support Repository** installed. Open the SDK manager and add the Android Support Repository to avoid the Frameworks detected notification. 65 | 5. Open AndroidManifest.xml 66 | * Replace *ENTER_YOUR_CLIENT_ID* in two places with the application id from the previous section. 67 | 6. Build the app and install the .APK on your device or emulator. 68 | 7. Enable the **Storage** permission for the installed sample app on your device or emulator 69 | 8. Download the test.jpg image located in: `android-java-connect-sample/app/src/main/res/drawable/test.jpg` to your device's external storage root folder. 70 | 71 | 72 | 73 | Once you've built the Connect sample, you can run it on an emulator or device. Pick a device with API level 16 or higher from the **Choose device** dialog. 74 | 75 | To learn more about the sample, see [Call Microsoft Graph in an Android app](https://developer.microsoft.com/en-us/graph/docs/concepts/android). 76 | 77 | 78 | ## Contributing ## 79 | 80 | If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md). 81 | 82 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 83 | 84 | ## Questions and comments 85 | 86 | We'd love to get your feedback about the Connect sample. You can send your questions and suggestions to us in the [Issues](issues) section of this repository. 87 | 88 | Questions about Microsoft Graph development in general should be posted to [Stack Overflow](http://stackoverflow.com/questions/tagged/MicrosoftGraph+API). Make sure that your questions or comments are tagged with [MicrosoftGraph] and [API]. 89 | 90 | ## Next steps 91 | 92 | This sample just shows the essentials that your apps need to work with Microsoft Graph. There is so much more that your apps can do using the Office 365 APIs, like helping your users to manage their work day with calendar, find just the information they need in all the files they store in OneDrive, or find the exact person they need from their list of contacts. We have more to share with you in the [Snippets sample for Android](../../../android-java-snippets-sample). 93 | 94 | ## Additional resources 95 | 96 | * [Get started with Office 365 APIs powered by Microsoft Graph](http://dev.office.com/getting-started/office365apis) 97 | * [Microsoft Graph overview](http://graph.microsoft.io) 98 | * [Microsoft Graph SDK for Android](../../../msgraph-sdk-android) 99 | * [Snippets sample for Android](../../../android-java-snippets-sample) 100 | 101 | ## Copyright 102 | Copyright (c) 2019 Microsoft. All rights reserved. 103 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 27 5 | defaultConfig { 6 | applicationId "com.microsoft.graph.connect" 7 | minSdkVersion 16 8 | targetSdkVersion 26 9 | versionCode 2 10 | versionName "2.0" 11 | multiDexEnabled true 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | testOptions { 21 | unitTests.returnDefaultValues = true 22 | } 23 | configurations { 24 | all { 25 | resolutionStrategy.force 'com.android.support:support-annotations:25.3.1' 26 | } 27 | } 28 | dexOptions { 29 | preDexLibraries = false 30 | jumboMode = true 31 | javaMaxHeapSize "4g" 32 | } 33 | packagingOptions { 34 | exclude 'META-INF/maven/com.google.guava/guava/pom.properties' 35 | exclude 'META-INF/maven/com.google.guava/guava/pom.xml' 36 | exclude 'META-INF/jersey-module-version' 37 | } 38 | } 39 | 40 | dependencies { 41 | implementation fileTree(include: ['*.jar'], dir: 'libs') 42 | testImplementation 'junit:junit:4.12' 43 | implementation 'com.android.support:appcompat-v7:27.0.0' 44 | implementation 'com.android.volley:volley:1.1.0' 45 | // Include the SDK as a dependency 46 | implementation 'com.microsoft.graph:microsoft-graph:1.2.0' 47 | implementation 'com.microsoft.graph:microsoft-graph-android-auth:0.1.0-SNAPSHOT' 48 | // Include GSON as a dependency 49 | implementation 'com.google.code.gson:gson:2.6.2' 50 | implementation 'commons-io:commons-io:2.0.1' 51 | // Test libraries 52 | androidTestImplementation 'com.android.support:support-annotations:25.3.1' 53 | androidTestImplementation 'com.android.support.test:runner:0.5' 54 | androidTestImplementation 'com.android.support.test:rules:0.5' 55 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2' 56 | androidTestImplementation 'com.android.support.test.espresso:espresso-intents:2.2.2' 57 | androidTestImplementation 'com.android.support.test.espresso:espresso-web:2.2.2' 58 | 59 | } 60 | -------------------------------------------------------------------------------- /app/gradle.properties: -------------------------------------------------------------------------------- 1 | test_client_id= 2 | test_username= 3 | test_password= 4 | 5 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/ricalo/Android/Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/getTestConfig.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | SET testConfig={ 4 | SET testConfig=%testConfig% "test_client_id": "%TEST_CLIENT_ID%", 5 | SET testConfig=%testConfig% "test_username": "%TEST_USERNAME%", 6 | SET testConfig=%testConfig% "test_password": "%1" 7 | SET testConfig=%testConfig% } 8 | echo %testConfig% 9 | echo %testConfig% > testConfig.json 10 | 11 | SET _adb_devices=%ANDROID_HOME%\platform-tools\adb.exe devices 12 | FOR /f "skip=1" %%G IN ('%_adb_devices%') DO %ANDROID_HOME%\platform-tools\adb.exe -s %%G push testConfig.json ./data/local 13 | -------------------------------------------------------------------------------- /app/src/androidTest/getTestConfig.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | testConfig="{ 4 | \"test_client_id\": \"$TEST_CLIENT_ID\", 5 | \"test_username\": \"$TEST_USERNAME\", 6 | \"test_password\": \"$1\" 7 | }" 8 | echo $testConfig 9 | echo $testConfig > testConfig.json 10 | 11 | adb devices | while read line 12 | do 13 | if [ ! "$line" = "" ] && [ `echo $line | awk '{print $2}'` = "device" ] 14 | then 15 | device=`echo $line | awk '{print $1}'` 16 | echo "$device $@ ..." 17 | adb -s $device push testConfig.json ./data/local 18 | fi 19 | done 20 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 23 | 24 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 39 | 42 | 43 | 44 | 46 | 47 | 48 | 49 | 50 | 52 | 53 | 54 | 57 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/AuthenticationManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the project root for license information. 4 | */ 5 | package com.microsoft.graph.connect; 6 | 7 | import android.accounts.AuthenticatorException; 8 | import android.accounts.OperationCanceledException; 9 | import android.app.Activity; 10 | import android.content.Context; 11 | import android.util.Log; 12 | 13 | import com.microsoft.graph.connect.util.IManifestReader; 14 | import com.microsoft.graph.connect.util.ManifestReader; 15 | import com.microsoft.identity.client.AuthenticationCallback; 16 | import com.microsoft.identity.client.AuthenticationResult; 17 | import com.microsoft.identity.client.IAccount; 18 | import com.microsoft.identity.client.exception.MsalException; 19 | import com.microsoft.identity.client.PublicClientApplication; 20 | 21 | import java.io.IOException; 22 | 23 | /** 24 | * Handles setup of OAuth library in API clients. 25 | */ 26 | public class AuthenticationManager { 27 | private static final String TAG = "AuthenticationManager"; 28 | private static AuthenticationManager INSTANCE; 29 | private static PublicClientApplication mPublicClientApplication; 30 | private AuthenticationResult mAuthResult; 31 | private MSALAuthenticationCallback mActivityCallback; 32 | private AuthenticationManager() { 33 | } 34 | 35 | public static synchronized AuthenticationManager getInstance() { 36 | if (INSTANCE == null) { 37 | INSTANCE = new AuthenticationManager(); 38 | 39 | IManifestReader metaDataReader = new ManifestReader(); 40 | String clientID = metaDataReader.getApplicationMetadataValueString("com.microsoft.identity.client.ClientId"); 41 | 42 | if (mPublicClientApplication == null) { 43 | mPublicClientApplication = new PublicClientApplication(Connect.getInstance(), clientID); 44 | } 45 | } 46 | return INSTANCE; 47 | } 48 | 49 | public static synchronized void resetInstance() { 50 | INSTANCE = null; 51 | } 52 | 53 | /** 54 | * Returns the access token obtained in authentication 55 | * 56 | * @return mAccessToken 57 | */ 58 | public String getAccessToken() throws AuthenticatorException, IOException, OperationCanceledException { 59 | return mAuthResult.getAccessToken(); 60 | } 61 | 62 | public PublicClientApplication getPublicClient(){ 63 | return mPublicClientApplication; 64 | } 65 | 66 | /** 67 | * Disconnects the app from Office 365 by clearing the token cache, setting the client objects 68 | * to null, and removing the user id from shred preferences. 69 | */ 70 | public void disconnect() { 71 | mPublicClientApplication.removeAccount(mAuthResult.getAccount()); 72 | // Reset the AuthenticationManager object 73 | AuthenticationManager.resetInstance(); 74 | } 75 | 76 | /** 77 | * Authenticates the user and lets the user authorize the app for the requested permissions. 78 | * An authentication token is returned via the getAuthInteractiveCalback method 79 | * @param activity 80 | * @param authenticationCallback 81 | */ 82 | public void callAcquireToken(Activity activity, final MSALAuthenticationCallback authenticationCallback) { 83 | mActivityCallback = authenticationCallback; 84 | mPublicClientApplication.acquireToken( 85 | activity, Constants.SCOPES, getAuthInteractiveCallback()); 86 | } 87 | public void callAcquireTokenSilent(IAccount account, boolean forceRefresh, MSALAuthenticationCallback msalAuthenticationCallback) { 88 | mActivityCallback = msalAuthenticationCallback; 89 | mPublicClientApplication.acquireTokenSilentAsync(Constants.SCOPES, account, null, forceRefresh, getAuthSilentCallback()); 90 | } 91 | // 92 | // App callbacks for MSAL 93 | // ====================== 94 | // getActivity() - returns activity so we can acquireToken within a callback 95 | // getAuthSilentCallback() - callback defined to handle acquireTokenSilent() case 96 | // getAuthInteractiveCallback() - callback defined to handle acquireToken() case 97 | // 98 | 99 | public Context getActivity() { 100 | return Connect.getContext(); 101 | } 102 | 103 | /* Callback method for acquireTokenSilent calls 104 | * Looks if tokens are in the cache (refreshes if necessary and if we don't forceRefresh) 105 | * else errors that we need to do an interactive request. 106 | */ 107 | private AuthenticationCallback getAuthSilentCallback() { 108 | return new AuthenticationCallback() { 109 | @Override 110 | public void onSuccess(AuthenticationResult authenticationResult) { 111 | /* Successfully got a token, call Graph now */ 112 | Log.d(TAG, "Successfully authenticated"); 113 | 114 | /* Store the authResult */ 115 | mAuthResult = authenticationResult; 116 | 117 | //invoke UI callback 118 | if (mActivityCallback != null) 119 | mActivityCallback.onSuccess(mAuthResult); 120 | } 121 | 122 | @Override 123 | public void onError(MsalException exception) { 124 | /* Failed to acquireToken */ 125 | Log.d(TAG, "Authentication failed: " + exception.toString()); 126 | if (mActivityCallback != null) 127 | mActivityCallback.onError(exception); 128 | } 129 | 130 | @Override 131 | public void onCancel() { 132 | /* User canceled the authentication */ 133 | Log.d(TAG, "User cancelled login."); 134 | } 135 | }; 136 | } 137 | 138 | 139 | /* Callback used for interactive request. If succeeds we use the access 140 | * token to call the Microsoft Graph. Does not check cache 141 | */ 142 | private AuthenticationCallback getAuthInteractiveCallback() { 143 | return new AuthenticationCallback() { 144 | @Override 145 | public void onSuccess(AuthenticationResult authenticationResult) { 146 | /* Successfully got a token, call graph now */ 147 | Log.d(TAG, "Successfully authenticated"); 148 | Log.d(TAG, "ID Token: " + authenticationResult.getIdToken()); 149 | 150 | /* Store the auth result */ 151 | mAuthResult = authenticationResult; 152 | if (mActivityCallback != null) 153 | mActivityCallback.onSuccess(mAuthResult); 154 | } 155 | 156 | @Override 157 | public void onError(MsalException exception) { 158 | /* Failed to acquireToken */ 159 | Log.d(TAG, "Authentication failed: " + exception.toString()); 160 | if (mActivityCallback != null) 161 | mActivityCallback.onError(exception); 162 | } 163 | 164 | @Override 165 | public void onCancel() { 166 | /* User canceled the authentication */ 167 | Log.d(TAG, "User cancelled login."); 168 | if (mActivityCallback != null) 169 | mActivityCallback.onCancel(); 170 | } 171 | }; 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/Connect.java: -------------------------------------------------------------------------------- 1 | package com.microsoft.graph.connect; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.os.StrictMode; 6 | import android.support.multidex.MultiDex; 7 | import android.support.multidex.MultiDexApplication; 8 | 9 | import com.microsoft.identity.client.ILoggerCallback; 10 | import com.microsoft.identity.client.Logger; 11 | 12 | public class Connect extends MultiDexApplication { 13 | public static Connect instance; 14 | 15 | public static Connect getInstance() { 16 | return instance; 17 | } 18 | 19 | public static Context getContext(){ 20 | return instance; 21 | } 22 | 23 | private Activity mConnectActivity; 24 | 25 | private StringBuffer mLogs; 26 | @Override 27 | protected void attachBaseContext(Context base) { 28 | super.attachBaseContext(base); 29 | MultiDex.install(this); 30 | } 31 | @Override 32 | public void onCreate(){ 33 | instance = this; 34 | super.onCreate(); 35 | 36 | mLogs = new StringBuffer(); 37 | StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 38 | StrictMode.setThreadPolicy(policy); 39 | 40 | // Logging can be turned on four different levels: error, warning, info, and verbose. By default the sdk is turning on 41 | // verbose level logging. Any apps can use Logger.getInstance().setLogLevel(Loglevel) to enable different level of logging. 42 | Logger.getInstance().setExternalLogger(new ILoggerCallback() { 43 | @Override 44 | public void log(String tag, Logger.LogLevel logLevel, String message, boolean containsPII) { 45 | // contains PII indicates that if the log message contains PII information. If Pii logging is 46 | // disabled, the sdk never returns back logs with Pii. 47 | mLogs.append(message).append('\n'); 48 | } 49 | }); 50 | } 51 | String getLogs() { 52 | return mLogs.toString(); 53 | } 54 | 55 | void clearLogs() { 56 | mLogs = new StringBuffer(); 57 | } 58 | 59 | public Activity getConnectActivity() { 60 | return mConnectActivity; 61 | } 62 | 63 | public void setConnectActivity(Activity connectActivity) { 64 | mConnectActivity = connectActivity; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/ConnectActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the project root for license information. 4 | */ 5 | package com.microsoft.graph.connect; 6 | 7 | import android.content.Intent; 8 | import android.os.Bundle; 9 | import android.os.Handler; 10 | import android.support.v7.app.AppCompatActivity; 11 | import android.util.Log; 12 | import android.view.View; 13 | import android.widget.Button; 14 | import android.widget.ProgressBar; 15 | import android.widget.TextView; 16 | import android.widget.Toast; 17 | 18 | import com.microsoft.identity.client.AuthenticationResult; 19 | import com.microsoft.identity.client.Logger; 20 | import com.microsoft.identity.client.exception.MsalException; 21 | import com.microsoft.identity.client.exception.MsalClientException; 22 | import com.microsoft.identity.client.exception.MsalServiceException; 23 | import com.microsoft.identity.client.exception.MsalUiRequiredException; 24 | import com.microsoft.identity.client.IAccount; 25 | 26 | import java.util.List; 27 | 28 | /** 29 | * Starting Activity of the app. Handles the connection to Office 365. 30 | * When it first starts it only displays a button to Connect to Office 365. 31 | * If there are no cached tokens, the user is required to sign in to Office 365. 32 | * If there are cached tokens, the app tries to reuse them. 33 | * The activity redirects the user to the SendMailActivity upon successful connection. 34 | */ 35 | public class ConnectActivity 36 | extends AppCompatActivity 37 | implements MSALAuthenticationCallback { 38 | 39 | private static final String TAG = "ConnectActivity"; 40 | 41 | private boolean mEnablePiiLogging = false; 42 | private IAccount mAccount; 43 | private Handler mHandler; 44 | 45 | private Button mConnectButton; 46 | private TextView mTitleTextView; 47 | private TextView mDescriptionTextView; 48 | private ProgressBar mConnectProgressBar; 49 | 50 | 51 | @Override 52 | protected void onCreate(Bundle savedInstanceState) { 53 | super.onCreate(savedInstanceState); 54 | 55 | 56 | Bundle extras = getIntent().getExtras(); 57 | setContentView(R.layout.activity_connect); 58 | setTitle(R.string.app_name); 59 | 60 | // set up our views 61 | mConnectButton = (Button) findViewById(R.id.connectButton); 62 | mConnectProgressBar = (ProgressBar) findViewById(R.id.connectProgressBar); 63 | mTitleTextView = (TextView) findViewById(R.id.titleTextView); 64 | mDescriptionTextView = (TextView) findViewById(R.id.descriptionTextView); 65 | 66 | Connect.getInstance().setConnectActivity(this); 67 | // add click listener 68 | mConnectButton.setOnClickListener(new View.OnClickListener() { 69 | @Override 70 | public void onClick(View v) { 71 | showConnectingInProgressUI(); 72 | connect(); 73 | } 74 | }); 75 | } 76 | 77 | private void connect() { 78 | 79 | // The sample app is having the PII enable setting on the MainActivity. Ideally, app should decide to enable Pii or not, 80 | // if it's enabled, it should be the setting when the application is onCreate. 81 | if (mEnablePiiLogging) { 82 | Logger.getInstance().setEnablePII(true); 83 | } else { 84 | Logger.getInstance().setEnablePII(false); 85 | } 86 | 87 | AuthenticationManager mgr = AuthenticationManager.getInstance(); 88 | 89 | /* Attempt to get a user and acquireTokenSilent 90 | * If this fails we do an interactive request 91 | */ 92 | List accounts = null; 93 | 94 | try { 95 | accounts = mgr.getPublicClient().getAccounts(); 96 | 97 | if (accounts != null && accounts.size() == 1) { 98 | /* We have 1 user */ 99 | mAccount = accounts.get(0); 100 | mgr.callAcquireTokenSilent( 101 | mAccount, 102 | true, 103 | this); 104 | } else { 105 | /* We have no user */ 106 | 107 | /* Let's do an interactive request */ 108 | mgr.callAcquireToken( 109 | this, 110 | this); 111 | } 112 | }catch (IndexOutOfBoundsException e) { 113 | Log.d(TAG, "User at this position does not exist: " + e.toString()); 114 | showConnectErrorUI(e.getMessage()); 115 | 116 | }catch (IllegalStateException e) { 117 | Log.d(TAG, "MSAL Exception Generated: " + e.toString()); 118 | showConnectErrorUI(e.getMessage()); 119 | 120 | } catch (Exception e) { 121 | showConnectErrorUI(); 122 | } 123 | } 124 | 125 | /** 126 | * Handles redirect response from https://login.microsoftonline.com/common and 127 | * notifies the MSAL library that the user has completed the authentication 128 | * dialog 129 | * @param requestCode 130 | * @param resultCode 131 | * @param data 132 | */ 133 | @Override 134 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 135 | super.onActivityResult(requestCode, resultCode, data); 136 | if (AuthenticationManager 137 | .getInstance() 138 | .getPublicClient() != null) { 139 | AuthenticationManager 140 | .getInstance() 141 | .getPublicClient() 142 | .handleInteractiveRequestRedirect(requestCode, resultCode, data); 143 | } 144 | } 145 | 146 | 147 | private void resetUIForConnect() { 148 | mConnectButton.setVisibility(View.VISIBLE); 149 | mTitleTextView.setVisibility(View.GONE); 150 | mDescriptionTextView.setVisibility(View.GONE); 151 | mConnectProgressBar.setVisibility(View.GONE); 152 | } 153 | 154 | private void showConnectingInProgressUI() { 155 | mConnectButton.setVisibility(View.GONE); 156 | mTitleTextView.setVisibility(View.GONE); 157 | mDescriptionTextView.setVisibility(View.GONE); 158 | mConnectProgressBar.setVisibility(View.VISIBLE); 159 | } 160 | 161 | private void showConnectErrorUI() { 162 | mConnectButton.setVisibility(View.VISIBLE); 163 | mConnectProgressBar.setVisibility(View.GONE); 164 | mTitleTextView.setText(R.string.title_text_error); 165 | mTitleTextView.setVisibility(View.VISIBLE); 166 | mDescriptionTextView.setText(R.string.connect_text_error); 167 | mDescriptionTextView.setVisibility(View.VISIBLE); 168 | Toast.makeText( 169 | ConnectActivity.this, 170 | R.string.connect_toast_text_error, 171 | Toast.LENGTH_LONG).show(); 172 | } 173 | private void showConnectErrorUI(String errorMessage) { 174 | mConnectButton.setVisibility(View.VISIBLE); 175 | mConnectProgressBar.setVisibility(View.GONE); 176 | mTitleTextView.setText(R.string.title_text_error); 177 | mTitleTextView.setVisibility(View.VISIBLE); 178 | mDescriptionTextView.setText(errorMessage); 179 | mDescriptionTextView.setVisibility(View.VISIBLE); 180 | Toast.makeText( 181 | ConnectActivity.this, 182 | R.string.connect_toast_text_error, 183 | Toast.LENGTH_LONG).show(); 184 | } 185 | 186 | private void showMessage(final String msg) { 187 | getHandler().post(new Runnable() { 188 | 189 | @Override 190 | public void run() { 191 | Toast.makeText(ConnectActivity.this, msg, Toast.LENGTH_LONG).show(); 192 | } 193 | }); 194 | } 195 | 196 | private Handler getHandler() { 197 | if (mHandler == null) { 198 | return new Handler(ConnectActivity.this.getMainLooper()); 199 | } 200 | 201 | return mHandler; 202 | } 203 | 204 | 205 | @Override 206 | public void onSuccess(AuthenticationResult authenticationResult) { 207 | mAccount = authenticationResult.getAccount(); 208 | 209 | String name = ""; 210 | String preferredUsername = ""; 211 | 212 | try { 213 | // get the user info from the id token 214 | name = authenticationResult.getAccount().getUsername(); 215 | preferredUsername = authenticationResult.getAccount().getUsername(); 216 | 217 | AuthenticationManager mgr = AuthenticationManager.getInstance(); 218 | 219 | 220 | } catch (NullPointerException npe) { 221 | Log.e(TAG, npe.getMessage()); 222 | 223 | } 224 | 225 | // Prepare the SendMailActivity intent 226 | Intent sendMailActivity = 227 | new Intent(ConnectActivity.this, SendMailActivity.class); 228 | 229 | // take the user's info along 230 | sendMailActivity.putExtra(SendMailActivity.ARG_GIVEN_NAME, name); 231 | sendMailActivity.putExtra(SendMailActivity.ARG_DISPLAY_ID, preferredUsername); 232 | 233 | 234 | // actually start the activity 235 | startActivity(sendMailActivity); 236 | 237 | new Thread(new Runnable() { 238 | @Override 239 | public void run() { 240 | resetUIForConnect(); 241 | } 242 | }); 243 | 244 | 245 | } 246 | 247 | @Override 248 | public void onError(MsalException exception) { 249 | // Check the exception type. 250 | if (exception instanceof MsalClientException) { 251 | // This means errors happened in the sdk itself, could be network, Json parse, etc. Check MsalError.java 252 | // for detailed list of the errors. 253 | showMessage(exception.getMessage()); 254 | showConnectErrorUI(exception.getMessage()); 255 | } else if (exception instanceof MsalServiceException) { 256 | // This means something is wrong when the sdk is communication to the service, mostly likely it's the client 257 | // configuration. 258 | showMessage(exception.getMessage()); 259 | showConnectErrorUI(exception.getMessage()); 260 | } else if (exception instanceof MsalUiRequiredException) { 261 | // This explicitly indicates that developer needs to prompt the user, it could be refresh token is expired, revoked 262 | // or user changes the password; or it could be that no token was found in the token cache. 263 | AuthenticationManager mgr = AuthenticationManager.getInstance(); 264 | 265 | 266 | mgr.callAcquireToken(ConnectActivity.this, this); 267 | } 268 | } 269 | 270 | @Override 271 | public void onError(Exception exception) { 272 | showMessage(exception.getMessage()); 273 | showConnectErrorUI(exception.getMessage()); 274 | } 275 | 276 | @Override 277 | public void onCancel() { 278 | showMessage("User cancelled the flow."); 279 | showConnectErrorUI("User cancelled the flow."); 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the project root for license information. 4 | */ 5 | package com.microsoft.graph.connect; 6 | 7 | public class Constants { 8 | public static final String AUTHORITY_URL = "https://login.microsoftonline.com/common"; 9 | public static final String AUTHORIZATION_ENDPOINT = "/oauth2/v2.0/authorize"; 10 | public static final String TOKEN_ENDPOINT = "/oauth2/v2.0/token"; 11 | // The Microsoft Graph delegated permissions that you set in the application 12 | // registration portal must match these scope values. 13 | // Update this constant with the scope (permission) values for your application: 14 | public static final String[] SCOPES = {"openid", "Mail.ReadWrite","mail.send","Files.ReadWrite","User.ReadBasic.All"}; 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/GraphServiceClientManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the project root for license information. 4 | */ 5 | package com.microsoft.graph.connect; 6 | 7 | import android.accounts.AuthenticatorException; 8 | import android.accounts.OperationCanceledException; 9 | import android.app.Activity; 10 | import android.app.Application; 11 | import android.util.Log; 12 | 13 | import com.microsoft.graph.authentication.IAuthenticationProvider; 14 | import com.microsoft.graph.authentication.MSALAuthenticationProvider; 15 | import com.microsoft.graph.requests.extensions.GraphServiceClient; 16 | import com.microsoft.graph.models.extensions.IGraphServiceClient; 17 | import com.microsoft.graph.http.IHttpRequest; 18 | 19 | import java.io.IOException; 20 | 21 | /** 22 | * Singleton class that manages a GraphServiceClient object. 23 | * It implements IAuthentication provider to authenticate requests using an access token. 24 | */ 25 | public class GraphServiceClientManager extends Application implements IAuthenticationProvider { 26 | private IGraphServiceClient mGraphServiceClient; 27 | private static GraphServiceClientManager INSTANCE; 28 | private AuthenticationManager mAuthenticationManager; 29 | private static Activity connectActivity; 30 | private MSALAuthenticationProvider msalAuthenticationProvider; 31 | private IGraphServiceClient graphClient; 32 | 33 | 34 | public static GraphServiceClientManager getApp() { 35 | return INSTANCE; 36 | } 37 | public static Activity getAppActivity() {return connectActivity;} 38 | 39 | private GraphServiceClientManager() { 40 | mAuthenticationManager = AuthenticationManager.getInstance(); 41 | } 42 | 43 | /** 44 | * Appends an access token obtained from the {@link AuthenticationManager} class to the 45 | * Authorization header of the request. 46 | * @param request 47 | */ 48 | @Override 49 | public void authenticateRequest(IHttpRequest request) { 50 | try { 51 | request.addHeader("Authorization", "Bearer " 52 | + AuthenticationManager.getInstance() 53 | .getAccessToken()); 54 | // This header has been added to identify this sample in the Microsoft Graph service. 55 | // If you're using this code for your project please remove the following line. 56 | request.addHeader("SampleID", "android-java-connect-sample"); 57 | 58 | Log.i("Connect","Request: " + request.toString()); 59 | } catch (AuthenticatorException e) { 60 | e.printStackTrace(); 61 | } catch (IOException e) { 62 | e.printStackTrace(); 63 | } catch (OperationCanceledException e) { 64 | e.printStackTrace(); 65 | } catch (NullPointerException e) { 66 | e.printStackTrace(); 67 | } 68 | } 69 | 70 | public static synchronized GraphServiceClientManager getInstance() { 71 | if(INSTANCE == null) { 72 | INSTANCE = new GraphServiceClientManager(); 73 | } 74 | return INSTANCE; 75 | } 76 | 77 | public synchronized IGraphServiceClient getGraphServiceClient() { 78 | return getGraphServiceClient(this); 79 | } 80 | 81 | public synchronized IGraphServiceClient getGraphServiceClient(IAuthenticationProvider authenticationProvider) { 82 | if (mGraphServiceClient == null) { 83 | if(msalAuthenticationProvider == null){ 84 | msalAuthenticationProvider = new MSALAuthenticationProvider( 85 | getAppActivity(), 86 | GraphServiceClientManager.getApp(), 87 | mAuthenticationManager.getPublicClient(), 88 | Constants.SCOPES); 89 | } 90 | if(graphClient == null){ 91 | graphClient = 92 | GraphServiceClient 93 | .builder() 94 | .authenticationProvider(msalAuthenticationProvider) 95 | .buildClient(); 96 | } 97 | return graphClient; 98 | } 99 | return mGraphServiceClient; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/GraphServiceController.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the project root for license information. 4 | */ 5 | package com.microsoft.graph.connect; 6 | 7 | import android.annotation.TargetApi; 8 | import android.app.AlertDialog; 9 | import android.content.DialogInterface; 10 | import android.graphics.Bitmap; 11 | import android.graphics.drawable.BitmapDrawable; 12 | import android.graphics.drawable.Drawable; 13 | import android.os.Build; 14 | import android.os.Environment; 15 | import android.os.NetworkOnMainThreadException; 16 | import android.support.annotation.VisibleForTesting; 17 | import android.util.Log; 18 | 19 | import com.microsoft.graph.concurrency.ICallback; 20 | import com.microsoft.graph.core.ClientException; 21 | import com.microsoft.graph.models.extensions.Attachment; 22 | import com.microsoft.graph.models.generated.BodyType; 23 | import com.microsoft.graph.models.extensions.DriveItem; 24 | import com.microsoft.graph.models.extensions.EmailAddress; 25 | import com.microsoft.graph.models.extensions.FileAttachment; 26 | import com.microsoft.graph.models.extensions.IGraphServiceClient; 27 | import com.microsoft.graph.models.extensions.ItemBody; 28 | import com.microsoft.graph.models.extensions.Message; 29 | import com.microsoft.graph.models.extensions.Permission; 30 | import com.microsoft.graph.models.extensions.Recipient; 31 | 32 | import org.apache.commons.io.output.ByteArrayOutputStream; 33 | 34 | import java.io.BufferedInputStream; 35 | import java.io.File; 36 | import java.io.FileInputStream; 37 | import java.io.FileNotFoundException; 38 | import java.io.IOException; 39 | import java.io.InputStream; 40 | import java.util.Collections; 41 | 42 | /** 43 | * Handles the creation of the message and using the GraphServiceClient to 44 | * send the message. The app must have connected to Office 365 before using the 45 | * {@link #createDraftMail(String, String, String, String, ICallback)}method. 46 | */ 47 | class GraphServiceController { 48 | 49 | 50 | public enum StorageState { 51 | NOT_AVAILABLE, WRITEABLE, READ_ONLY 52 | } 53 | 54 | private final IGraphServiceClient mGraphServiceClient; 55 | 56 | public GraphServiceController() { 57 | mGraphServiceClient = GraphServiceClientManager.getInstance().getGraphServiceClient(); 58 | } 59 | 60 | /** 61 | * Creates a draft email message using the Microsoft Graph API on Office 365. The mail is sent 62 | * from the address of the signed in user. 63 | * 64 | * @param senderPreferredName The mail senders principal user name (email addr) 65 | * @param emailAddress The recipient email address. 66 | * @param subject The subject to use in the mail message. 67 | * @param body The body of the message. 68 | * @param callback The callback method to invoke on completion of the POST request 69 | */ 70 | public void createDraftMail( 71 | final String senderPreferredName, 72 | final String emailAddress, 73 | final String subject, 74 | final String body, 75 | ICallback callback 76 | ) { 77 | try { 78 | // create the email message 79 | Message message = createMessage(subject, body, emailAddress); 80 | mGraphServiceClient 81 | .me() 82 | .messages() 83 | .buildRequest() 84 | .post(message, callback); 85 | 86 | } catch (Exception ex) { 87 | showException(ex, "exception on send mail","Send mail failed", "The send mail method failed"); 88 | } 89 | } 90 | 91 | /** 92 | * Posts a file attachment in a draft message by message Id 93 | * 94 | * @param messageId String. The id of the draft message to add an attachment to 95 | * @param picture Byte[]. The picture in bytes 96 | * @param sharingLink String. The sharing link to the uploaded picture 97 | * @param callback 98 | */ 99 | public void addPictureToDraftMessage(String messageId, 100 | byte[] picture, 101 | String sharingLink, 102 | ICallback callback) { 103 | try { 104 | byte[] attachementBytes = new byte[picture.length]; 105 | 106 | if (picture.length > 0) { 107 | attachementBytes = picture; 108 | } else { 109 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){ 110 | attachementBytes = getDefaultPicture(); 111 | } 112 | else { 113 | attachementBytes = getTestPicture(); 114 | } 115 | } 116 | 117 | FileAttachment fileAttachment = new FileAttachment(); 118 | fileAttachment.oDataType = "#microsoft.graph.fileAttachment"; 119 | fileAttachment.contentBytes = attachementBytes; 120 | //fileAttachment.contentType = "image/png"; 121 | fileAttachment.name = "me.png"; 122 | fileAttachment.size = attachementBytes.length; 123 | fileAttachment.isInline = false; 124 | fileAttachment.id = "blabla"; 125 | Log.i("connect sample","attachement id " + fileAttachment.id); 126 | mGraphServiceClient 127 | .me() 128 | .messages(messageId) 129 | .attachments() 130 | .buildRequest() 131 | .post(fileAttachment, callback); 132 | 133 | } catch (Exception ex) { 134 | showException(ex, "exception on add picture to draft message","Draft attachment failed", "The post file attachment method failed"); 135 | } 136 | } 137 | 138 | /** 139 | * Sends a draft message to the specified recipients 140 | * 141 | * @param messageId String. The id of the message to send 142 | * @param callback 143 | */ 144 | public void sendDraftMessage(String messageId, 145 | ICallback callback) { 146 | try { 147 | 148 | mGraphServiceClient 149 | .me() 150 | .messages(messageId) 151 | .send() 152 | .buildRequest() 153 | .post(callback); 154 | 155 | } catch (Exception ex) { 156 | showException(ex, "exception on send draft message ","Send draft mail failed", "The send draft mail method failed"); 157 | } 158 | } 159 | 160 | /** 161 | * Gets a draft message by message id 162 | * @param messageId 163 | * @param callback 164 | */ 165 | public void getDraftMessage(String messageId, ICallback callback) { 166 | try { 167 | mGraphServiceClient.me() 168 | .messages(messageId) 169 | .buildRequest() 170 | .get(callback); 171 | 172 | } catch (Exception ex) { 173 | showException(ex, "exception on get draft message ","Get draft mail failed", "The get draft mail method failed"); 174 | 175 | } 176 | } 177 | /** 178 | * Gets the profile picture of the signed in user from the Microsoft Graph 179 | * 180 | * @param callback 181 | */ 182 | public void getUserProfilePicture(final ICallback callback) { 183 | try { 184 | mGraphServiceClient 185 | .me() 186 | .photo() 187 | .content() 188 | .buildRequest() 189 | .get(new ICallback() { 190 | 191 | @Override 192 | public void success(final InputStream inputStream) { 193 | try { 194 | byte[] pictureBytes = new byte[1024]; 195 | BufferedInputStream bufferedInputStream = (BufferedInputStream) inputStream; 196 | byte[] buff = new byte[8000]; 197 | 198 | 199 | ByteArrayOutputStream bao = new ByteArrayOutputStream(); 200 | int bytesRead = 0; 201 | byte[] data = new byte[0]; 202 | try { 203 | //This seems to be executing on the main thread!!! 204 | while ((bytesRead = bufferedInputStream.read(buff)) != -1) { 205 | bao.write(buff, 0, bytesRead); 206 | } 207 | data = bao.toByteArray(); 208 | 209 | } catch (NetworkOnMainThreadException ex) { 210 | Log.e("Connect" , "Attempting to read buffered network resource on main thread " + ex.getMessage()); 211 | 212 | } 213 | 214 | 215 | 216 | 217 | //If the user's photo is not available, get the default test.jpg from the device external 218 | //storage root folder 219 | // if (bufferedInputStream.available() < 1) { 220 | if (data.length == 0) 221 | { 222 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){ 223 | pictureBytes = getDefaultPicture(); 224 | } 225 | else { 226 | pictureBytes = getTestPicture(); 227 | } 228 | } else { 229 | pictureBytes = data; //convertBufferToBytes(bufferedInputStream, inputStream.available()); 230 | } 231 | callback.success(pictureBytes); 232 | } catch (IOException e) { 233 | e.printStackTrace(); 234 | } 235 | } 236 | 237 | @Override 238 | public void failure(ClientException ex) { 239 | Log.e("GraphServiceController", "no picture found " + ex.getLocalizedMessage()); 240 | byte[] pictureBytes = new byte[1024]; 241 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){ 242 | pictureBytes = getDefaultPicture(); 243 | } 244 | else { 245 | pictureBytes = getTestPicture(); 246 | } 247 | 248 | if (pictureBytes.length > 0) { 249 | callback.success(pictureBytes); 250 | } else { 251 | callback.failure(ex); 252 | } 253 | } 254 | }); 255 | } catch (Exception ex) { 256 | showException(ex, "exception on get user profile picture ","Get user profile picture failed", "The get user profile picture method failed"); 257 | } 258 | } 259 | 260 | @VisibleForTesting 261 | 262 | /** 263 | * Creates a new Message object 264 | */ 265 | Message createMessage( 266 | String subject, 267 | String body, 268 | String address) { 269 | 270 | if (address == null || address.isEmpty()) { 271 | throw new IllegalArgumentException("The address parameter can't be null or empty."); 272 | } else { 273 | // perform a simple validation of the email address 274 | String addressParts[] = address.split("@"); 275 | if (addressParts.length != 2 || addressParts[0].length() == 0 || addressParts[1].indexOf('.') == -1) { 276 | throw new IllegalArgumentException( 277 | String.format("The address parameter must be a valid email address {0}", address) 278 | ); 279 | } 280 | } 281 | Message message = new Message(); 282 | EmailAddress emailAddress = new EmailAddress(); 283 | emailAddress.address = address; 284 | Recipient recipient = new Recipient(); 285 | recipient.emailAddress = emailAddress; 286 | message.toRecipients = Collections.singletonList(recipient); 287 | ItemBody itemBody = new ItemBody(); 288 | itemBody.content = body; 289 | itemBody.contentType = BodyType.HTML; 290 | message.body = itemBody; 291 | message.subject = subject; 292 | return message; 293 | } 294 | 295 | 296 | /** 297 | * Uploads a user picture as byte array to the user's OneDrive root folder 298 | * 299 | * @param picture byte[] picture byte array 300 | * @param callback 301 | */ 302 | public void uploadPictureToOneDrive(byte[] picture, ICallback callback) { 303 | 304 | try { 305 | mGraphServiceClient 306 | .me() 307 | .drive() 308 | .root() 309 | .itemWithPath("me.png") 310 | .content() 311 | .buildRequest() 312 | .put(picture, callback); 313 | } catch (Exception ex) { 314 | showException(ex, "exception on upload picture to OneDrive ","Upload picture failed", "The upload picture method failed"); 315 | } 316 | } 317 | 318 | public void getSharingLink(String id, ICallback callback) { 319 | 320 | try { 321 | 322 | mGraphServiceClient 323 | .me() 324 | .drive() 325 | .items(id) 326 | .createLink("view", "organization") 327 | .buildRequest() 328 | .post(callback); 329 | } catch (Exception ex) { 330 | showException(ex, "exception on get OneDrive sharing link ","Get sharing link failed", "The get sharing link method failed"); 331 | } 332 | } 333 | 334 | /** 335 | * Gets a picture from the device external storage root folder 336 | * 337 | * @return byte[] the default picture in a byte array 338 | */ 339 | private byte[] getDefaultPicture() { 340 | 341 | 342 | int bytesRead; 343 | byte[] bytes = new byte[1024]; 344 | 345 | String pathName = Environment.getExternalStorageDirectory() + "/"; 346 | String fileName = Connect.getContext().getString(R.string.defaultImageFileName); 347 | File file = new File(pathName, fileName); 348 | FileInputStream buf = null; 349 | if (file.exists() && file.canRead()) { 350 | int size = (int) file.length(); 351 | 352 | bytes = new byte[size]; 353 | try { 354 | buf = new FileInputStream(file); 355 | bytesRead = buf.read(bytes, 0, size); 356 | } catch (FileNotFoundException e) { 357 | // TODO Auto-generated catch block 358 | e.printStackTrace(); 359 | } catch (IOException e) { 360 | // TODO Auto-generated catch block 361 | e.printStackTrace(); 362 | } 363 | } 364 | return bytes; 365 | } 366 | 367 | @TargetApi(21) 368 | private byte[] getTestPicture() { 369 | byte[] bytes = new byte[1024]; 370 | int resId = Connect.getInstance().getResources().getIdentifier("test","drawable",Connect.getInstance().getPackageName()); 371 | Drawable image = Connect.getInstance().getDrawable(resId); 372 | Bitmap bitmap = ((BitmapDrawable)image).getBitmap(); 373 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 374 | bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream); 375 | bytes = stream.toByteArray(); 376 | return bytes; 377 | } 378 | /** 379 | * Gets the mounted state of device external storage 380 | * 381 | * @return 382 | */ 383 | private StorageState getExternalStorageState() { 384 | StorageState result = StorageState.NOT_AVAILABLE; 385 | String state = Environment.getExternalStorageState(); 386 | 387 | if (Environment.MEDIA_MOUNTED.equals(state)) { 388 | return StorageState.WRITEABLE; 389 | } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 390 | return StorageState.READ_ONLY; 391 | } 392 | return result; 393 | } 394 | 395 | /** 396 | * Converts a BufferedInputStream to a byte array 397 | * 398 | * @param inputStream 399 | * @param bufferLength 400 | * @return 401 | * @throws IOException 402 | */ 403 | private byte[] convertBufferToBytes(BufferedInputStream inputStream, int bufferLength) throws IOException { 404 | if (inputStream == null) 405 | return null; 406 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 407 | byte[] buffer = new byte[bufferLength]; 408 | int x = inputStream.read(buffer, 0, bufferLength); 409 | Log.i("GraphServiceController", "bytes read from picture input stream " + String.valueOf(x)); 410 | 411 | int n = 0; 412 | try { 413 | while ((n = inputStream.read(buffer, 0, bufferLength)) >= 0) { 414 | outputStream.write(buffer, 0, n); 415 | } 416 | inputStream.close(); 417 | } catch (IOException e) { 418 | e.printStackTrace(); 419 | } 420 | 421 | outputStream.close(); 422 | return outputStream.toByteArray(); 423 | } 424 | 425 | /* 426 | * Opens a user dialog that shows the failure result of an exception and writes a log entry 427 | * */ 428 | private void showException(Exception ex, String exceptionAction, String exceptionTitle, String exceptionMessage){ 429 | Log.e("GraphServiceController", exceptionAction + ex.getLocalizedMessage()); 430 | AlertDialog.Builder alertDialogBuidler = new AlertDialog.Builder(Connect.getContext()); 431 | alertDialogBuidler.setTitle(exceptionTitle); 432 | alertDialogBuidler.setMessage(exceptionMessage); 433 | alertDialogBuidler.setNeutralButton("Ok", new DialogInterface.OnClickListener() { 434 | @Override 435 | public void onClick(DialogInterface dialog, int which) { 436 | } 437 | }); 438 | alertDialogBuidler.show(); 439 | 440 | } 441 | } -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/MSALAuthenticationCallback.java: -------------------------------------------------------------------------------- 1 | package com.microsoft.graph.connect; 2 | 3 | import com.microsoft.identity.client.AuthenticationResult; 4 | import com.microsoft.identity.client.exception.MsalException; 5 | 6 | /** 7 | * Created by johnaustin on 7/5/17. 8 | */ 9 | 10 | interface MSALAuthenticationCallback { 11 | void onSuccess(AuthenticationResult authenticationResult); 12 | void onError(MsalException exception); 13 | void onError(Exception exception); 14 | void onCancel(); 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/SendMailActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the project root for license information. 4 | */ 5 | package com.microsoft.graph.connect; 6 | 7 | import android.content.Intent; 8 | import android.os.Bundle; 9 | import android.support.v7.app.AppCompatActivity; 10 | import android.util.Log; 11 | import android.view.Menu; 12 | import android.view.MenuItem; 13 | import android.view.View; 14 | import android.widget.Button; 15 | import android.widget.EditText; 16 | import android.widget.ProgressBar; 17 | import android.widget.TextView; 18 | import android.widget.Toast; 19 | 20 | import com.microsoft.graph.concurrency.ICallback; 21 | import com.microsoft.graph.core.ClientException; 22 | import com.microsoft.graph.models.extensions.Attachment; 23 | import com.microsoft.graph.models.extensions.DriveItem; 24 | import com.microsoft.graph.models.extensions.Message; 25 | import com.microsoft.graph.models.extensions.Permission; 26 | 27 | /** 28 | * This activity handles the send mail operation of the app. 29 | * The app must be connected to Office 365 before this activity can send an email. 30 | * It also uses the GraphServiceController to send the message. 31 | */ 32 | public class SendMailActivity extends AppCompatActivity { 33 | 34 | // arguments for this activity 35 | public static final String ARG_GIVEN_NAME = "givenName"; 36 | public static final String ARG_DISPLAY_ID = "displayableId"; 37 | public static final String ARG_UPN = "upn"; 38 | 39 | // views 40 | private EditText mEmailEditText; 41 | private Button mSendMailButton; 42 | private ProgressBar mSendMailProgressBar; 43 | private String mGivenName; 44 | private String mPreferredName; 45 | private TextView mConclusionTextView; 46 | final private GraphServiceController mGraphServiceController = new GraphServiceController(); 47 | 48 | 49 | @Override 50 | protected void onCreate(Bundle savedInstanceState) { 51 | super.onCreate(savedInstanceState); 52 | setContentView(R.layout.activity_send_mail); 53 | 54 | // find the views 55 | TextView mTitleTextView = (TextView) findViewById(R.id.titleTextView); 56 | mEmailEditText = (EditText) findViewById(R.id.emailEditText); 57 | mSendMailButton = (Button) findViewById(R.id.sendMailButton); 58 | mSendMailProgressBar = (ProgressBar) findViewById(R.id.sendMailProgressBar); 59 | mConclusionTextView = (TextView) findViewById(R.id.conclusionTextView); 60 | 61 | // Extract the givenName and displayableId and use it in the UI. 62 | mGivenName = getIntent().getStringExtra(ARG_GIVEN_NAME); 63 | mTitleTextView.append(mGivenName + "!"); 64 | mEmailEditText.setText(getIntent().getStringExtra(ARG_DISPLAY_ID)); 65 | mPreferredName = getIntent().getStringExtra(ARG_DISPLAY_ID); 66 | } 67 | 68 | /** 69 | * Handler for the onclick event of the send mail button. It uses the GraphServiceController to 70 | * send an email. When the call is completed, the call will return to either the success() 71 | * or failure() methods in this class which will then take the next steps on the UI. 72 | * This method sends the email using the address stored in the mEmailEditText view. 73 | * The subject and body of the message is stored in the strings.xml file. 74 | *

75 | * The following calls are made asynchronously in a chain of callback invocations. 76 | * 1. Get the user's profile picture from Microsoft Graph 77 | * 2. Upload the profile picture to the user's OneDrive root folder 78 | * 3. Get a sharing link to the picture from OneDrive 79 | * 4. Create and post a draft email 80 | * 5. Get the draft message 81 | * 6. Attach the profile picture to the draft mail as a byte array 82 | * 7. Send the draft email 83 | * 84 | * @param v The view. 85 | */ 86 | public void onSendMailButtonClick(View v) { 87 | try { 88 | resetUIForSendMail(); 89 | 90 | //1. Get the signed in user's profile picture 91 | mGraphServiceController.getUserProfilePicture(new ICallback() { 92 | @Override 93 | public void success(final byte[] bytes) { 94 | 95 | //2. Upload the profile picture to OneDrive 96 | mGraphServiceController.uploadPictureToOneDrive(bytes, new ICallback() { 97 | @Override 98 | public void success(DriveItem driveItem) { 99 | 100 | //3. Get the sharing link and if success, call step 4 helper 101 | Log.i("SendMailActivity", "Getting the sharing link "); 102 | getSharingLink(driveItem, bytes); 103 | } 104 | 105 | @Override 106 | public void failure(ClientException ex) { 107 | Log.i("SendMailActivity", "Exception on upload image to OneDrive " + ex.getLocalizedMessage()); 108 | showSendMailErrorUI(); 109 | } 110 | }); 111 | } 112 | 113 | @Override 114 | public void failure(ClientException ex) { 115 | showSendMailErrorUI(); 116 | } 117 | }); 118 | } catch (Exception ex) { 119 | Log.i("SendMailActivity", "Exception on send mail " + ex.getLocalizedMessage()); 120 | } 121 | } 122 | 123 | @Override 124 | public boolean onCreateOptionsMenu(Menu menu) { 125 | // Inflate the menu; this adds items to the action bar if it is present. 126 | getMenuInflater().inflate(R.menu.send_mail, menu); 127 | return true; 128 | } 129 | 130 | @Override 131 | public boolean onOptionsItemSelected(MenuItem item) { 132 | switch (item.getItemId()) { 133 | case R.id.disconnectMenuItem: 134 | AuthenticationManager.getInstance().disconnect(); 135 | Intent connectIntent = new Intent(this, ConnectActivity.class); 136 | startActivity(connectIntent); 137 | finish(); 138 | return true; 139 | default: 140 | return super.onOptionsItemSelected(item); 141 | } 142 | } 143 | 144 | /** 145 | * Gets the picture sharing link from OneDrive and calls the step 4 helper 146 | * 147 | * @param driveItem 148 | * @param bytes 149 | */ 150 | private void getSharingLink(DriveItem driveItem, final byte[] bytes) { 151 | //3. Get a sharing link to the picture uploaded to OneDrive 152 | mGraphServiceController.getSharingLink(driveItem.id, new ICallback() { 153 | @Override 154 | public void success(final Permission permission) { 155 | Log.i("SendMailActivity", "Creating the draft message "); 156 | createDraftMail(permission, bytes); 157 | } 158 | @Override 159 | public void failure(ClientException ex) { 160 | Log.i("SendMailActivity", "Exception on get sharing link " + ex.getLocalizedMessage()); 161 | showSendMailErrorUI(); 162 | } 163 | }); 164 | } 165 | 166 | /** 167 | * Creates a draft mail and calls the step 5 helper 168 | * 169 | * @param permission 170 | * @param bytes 171 | */ 172 | private void createDraftMail(final Permission permission, final byte[] bytes) { 173 | //Prepare body message and insert name of sender 174 | String body = getString(R.string.mail_body_text2); 175 | 176 | try { 177 | //insert sharing link instead of given name 178 | body = getString(R.string.mail_body_text2); 179 | 180 | //replace() is used instead of format() because the mail body string contains several 181 | //'%' characters, most of which are not string place holders. When format() is used, 182 | //format exception is thrown. Place holders do not match replacement parameters. 183 | body = body.replace("a href=%s", "a href=" + permission.link.webUrl.toString()); 184 | final String mailBody = body; 185 | //4. Create a draft mail message 186 | mGraphServiceController.createDraftMail( 187 | mPreferredName, 188 | mEmailEditText.getText().toString(), 189 | getString(R.string.mail_subject_text), 190 | mailBody, 191 | new ICallback() { 192 | @Override 193 | public void success(final Message aMessage) { 194 | Log.i("SendMailActivity", "Getting the draft message "); 195 | getDraftMessage(aMessage, permission, bytes); 196 | } 197 | 198 | @Override 199 | public void failure(ClientException ex) { 200 | Log.i("SendMailActivity", "Create draft mail " + ex.getLocalizedMessage()); 201 | showSendMailErrorUI(); 202 | } 203 | } 204 | ); 205 | } catch (Exception ex) { 206 | Log.i("SendMailActivity", "Exception on send mail " + ex.getLocalizedMessage()); 207 | showSendMailErrorUI(); 208 | 209 | } 210 | } 211 | 212 | /** 213 | * Gets the draft message created in the previous step and calls the step 6 helper 214 | * 215 | * @param aMessage 216 | * @param permission 217 | * @param bytes 218 | */ 219 | private void getDraftMessage(final Message aMessage, final Permission permission, final byte[] bytes) { 220 | //5. Get draft message 221 | mGraphServiceController.getDraftMessage(aMessage.id, new ICallback() { 222 | public void success(final Message aMessage) { 223 | Log.i("SendMailActivity", "Adding picture to draft message "); 224 | sendDraftMessage(aMessage); 225 | 226 | } 227 | 228 | public void failure(ClientException ex) { 229 | Log.i("SendMailActivity", "Exception on get draft message " + ex.getLocalizedMessage()); 230 | showSendMailErrorUI(); 231 | 232 | } 233 | }); 234 | } 235 | 236 | /** 237 | * Adds the picture bytes as attachment to the draft message and calls the step 7 helper 238 | * 239 | * @param aMessage 240 | * @param permission 241 | * @param bytes 242 | */ 243 | private void addPictureToDraftMessage(final Message aMessage, final Permission permission, final byte[] bytes) { 244 | //6. Add the profile picture to the draft mail 245 | mGraphServiceController.addPictureToDraftMessage(aMessage.id, bytes, permission.link.webUrl, 246 | new ICallback() { 247 | @Override 248 | public void success(final Attachment anAttachment) { 249 | Log.i("SendMailActivity", "Sending draft message "); 250 | sendDraftMessage(aMessage); 251 | } 252 | 253 | @Override 254 | public void failure(ClientException ex) { 255 | Log.i("SendMailActivity", "Exception on add picture to draft message " + ex.getLocalizedMessage()); 256 | showSendMailErrorUI(); 257 | } 258 | }); 259 | } 260 | 261 | /** 262 | * Sends the draft message 263 | * 264 | * @param aMessage 265 | */ 266 | private void sendDraftMessage(final Message aMessage) { 267 | //7. Send the draft message to the recipient 268 | mGraphServiceController.sendDraftMessage(aMessage.id, new ICallback() { 269 | @Override 270 | public void success(Void aVoid) { 271 | showSendMailSuccessUI(); 272 | } 273 | 274 | @Override 275 | public void failure(ClientException ex) { 276 | Log.i("SendMailActivity", "Exception on send draft message " + ex.getLocalizedMessage()); 277 | showSendMailErrorUI(); 278 | 279 | } 280 | }); 281 | 282 | } 283 | 284 | private void resetUIForSendMail() { 285 | mSendMailButton.setVisibility(View.GONE); 286 | mConclusionTextView.setVisibility(View.GONE); 287 | mSendMailProgressBar.setVisibility(View.VISIBLE); 288 | } 289 | 290 | private void showSendMailSuccessUI() { 291 | runOnUiThread(new Runnable() { 292 | @Override 293 | public void run() { 294 | mSendMailProgressBar.setVisibility(View.GONE); 295 | mSendMailButton.setVisibility(View.VISIBLE); 296 | mConclusionTextView.setText(R.string.conclusion_text); 297 | mConclusionTextView.setVisibility(View.VISIBLE); 298 | Toast.makeText( 299 | SendMailActivity.this, 300 | R.string.send_mail_toast_text, 301 | Toast.LENGTH_SHORT).show(); 302 | } 303 | }); 304 | } 305 | 306 | private void showSendMailErrorUI() { 307 | runOnUiThread(new Runnable() { 308 | @Override 309 | public void run() { 310 | mSendMailProgressBar.setVisibility(View.GONE); 311 | mSendMailButton.setVisibility(View.VISIBLE); 312 | mConclusionTextView.setText(R.string.send_mail_text_error); 313 | mConclusionTextView.setVisibility(View.VISIBLE); 314 | Toast.makeText( 315 | SendMailActivity.this, 316 | R.string.send_mail_toast_text_error, 317 | Toast.LENGTH_LONG).show(); 318 | } 319 | }); 320 | } 321 | } 322 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/TokenNotFoundException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the project root for license information. 4 | */ 5 | package com.microsoft.graph.connect; 6 | 7 | /** 8 | * Exception to throw when a token is not available in Authentication Manager. 9 | */ 10 | public class TokenNotFoundException extends Exception { 11 | public TokenNotFoundException() { 12 | super(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/UiBehavior.java: -------------------------------------------------------------------------------- 1 | package com.microsoft.graph.connect; 2 | 3 | /** 4 | * The UI options that developer could pass in during interactive sign in. 5 | */ 6 | 7 | public enum UiBehavior { 8 | 9 | /** 10 | * AcquireToken will send prompt=select_account to authorize endpoint and would show a list of users from which can be 11 | * selected for authentication. 12 | */ 13 | SELECT_ACCOUNT, 14 | 15 | /** 16 | * The user will be prompted for credentials by the service. It is achieved by sending prompt=login to the service. 17 | */ 18 | FORCE_LOGIN, 19 | 20 | /** 21 | * The user will be prompted to consent even if consent was granted before. It is achieved by sending prompt=consent 22 | * to the service. 23 | */ 24 | CONSENT 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/util/IManifestReader.java: -------------------------------------------------------------------------------- 1 | package com.microsoft.graph.connect.util; 2 | 3 | public interface IManifestReader { 4 | String getApplicationMetadataValueString(String key); 5 | } 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/java/com/microsoft/graph/connect/util/ManifestReader.java: -------------------------------------------------------------------------------- 1 | package com.microsoft.graph.connect.util; 2 | 3 | 4 | import android.content.pm.PackageInfo; 5 | import android.content.pm.PackageManager; 6 | import android.os.Bundle; 7 | 8 | import com.microsoft.graph.connect.Connect; 9 | 10 | 11 | /* 12 | Contains methods that access the application manifest 13 | */ 14 | public class ManifestReader implements IManifestReader{ 15 | 16 | /** 17 | * Gets the value of an AndroidManifest meta-data node. If the node value cannot be cast to String, 18 | * null is returned. 19 | * @param key String. The meta-data key value 20 | * @return String. The value associated with the key 21 | */ 22 | @Override 23 | public String getApplicationMetadataValueString(String key) { 24 | String returnValue = ""; 25 | try { 26 | PackageInfo info = Connect.getContext().getPackageManager().getPackageInfo( 27 | Connect.getContext().getPackageName(), 28 | PackageManager.GET_META_DATA); 29 | if (info.applicationInfo.metaData != null) { 30 | Bundle bundle = info.applicationInfo.metaData; 31 | returnValue = bundle.getString(key); 32 | } 33 | } catch (Exception e) { 34 | e.printStackTrace(); 35 | } 36 | return returnValue; 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 5 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/android-java-connect-sample/6cc6f1cb6d74db1a41f6f96eeb54531bb48658eb/app/src/main/res/drawable/test.jpg -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_connect.xml: -------------------------------------------------------------------------------- 1 | 5 | 15 | 16 |