文章同步自http://javaexception.com/archives/34html
如何給本身的app添加分享到有道雲筆記這樣的功能java
在以前的一個開源筆記類項目Leanote中,有個用戶反饋想增長相似分享到有道雲筆記的功能,這樣就能夠把本身小米便籤或者是其餘記事本的內容分享到Leanote中。android
那麼如何實現呢。須要有一個Activity來接受傳遞過來的內容,同時也須要在androidManifest.xml文件中配置。git
<activity android:name=".ui.edit.NoteEditActivity" android:screenOrientation="portrait" android:configChanges="uiMode|keyboard|keyboardHidden" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter> </activity>
接着咱們須要考慮的是如何獲取傳遞過來的內容。先提供一個處理Intent裏面內容的工具類。github
/** * Utilities for creating a share intent */ public class ShareUtils { /** * Create intent with subject and body * * @param subject * @param body * @return intent */ public static Intent create(final CharSequence subject, final CharSequence body) { Intent intent = new Intent(ACTION_SEND); intent.setType("text/plain"); if (!TextUtils.isEmpty(subject)) intent.putExtra(EXTRA_SUBJECT, subject); intent.putExtra(EXTRA_TEXT, body); return intent; } /** * Get body from intent * * @param intent * @return body */ public static String getBody(final Intent intent) { return intent != null ? intent.getStringExtra(EXTRA_TEXT) : null; } /** * Get subject from intent * * @param intent * @return subject */ public static String getSubject(final Intent intent) { return intent != null ? intent.getStringExtra(EXTRA_SUBJECT) : null; } }
獲取分享的內容,並在當前頁面展現數據庫
public Note getNoteFromShareIntent() { Note newNote = new Note(); Account account = Account.getCurrent(); newNote.setUserId(account.getUserId()); newNote.setTitle(ShareUtils.getSubject(getIntent())); newNote.setContent(ShareUtils.getBody(getIntent())); Notebook notebook; notebook = NotebookDataStore.getRecentNoteBook(account.getUserId()); if (notebook != null) { newNote.setNoteBookId(notebook.getNotebookId()); } else { Exception exception = new IllegalStateException("notebook is null"); CrashReport.postCatchedException(exception); } newNote.setIsMarkDown(account.getDefaultEditor() == Account.EDITOR_MARKDOWN); newNote.save(); return newNote; }
總結一下,就是須要在androidManifest.xml裏面配置支持text/plain的特定intent-filter,而後有個Activity與之對應,他來接收數據,接着就是獲取到接收的數據,結合具體的業務邏輯作後續的處理,如保存到本地數據庫,或者是展現在當前頁面等。app
看到了吧,這並無想象中的那麼難。工具