2014-02-28 67 views
0

我試圖將數據傳遞給我的活動,但不幸的是我仍然不成功。我試圖完成的是在文件瀏覽器中選擇一個文件,共享它並將數據傳遞給我的活動。使用「通過共享」屏幕將數據傳遞給活動

在我的清單我增加了一個意圖過濾器:

<activity android:name=".MyActivity" android:label="@string/app_name"> 
    <intent-filter> 
     <action android:name="android.intent.action.SEND"/> 
     <category android:name="android.intent.category.DEFAULT"/> 
     <data android:mimeType="*/*"/> 
    </intent-filter>    
</activity> 

裏面我的Java文件我試圖獲取數據:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.myactivity); 
    Intent intent = getIntent(); 
    Uri data = intent.getData(); 
    if (data != null) { 
     // process the data 
    } else { 
     // no data received 
    } 
} 

當我從我的文件和共享選擇一個文件它,我的應用程序是可見的列表中,當我點擊它啓動我的活動,但intent.getData();總是返回null。 我錯過了什麼?謝謝。

回答

0

你可以從下面給出的例子中獲得數據:

使用一個元素。例如,要處理所有鏈接到twitter.com,你把這個你裏面的AndroidManifest.xml:

<intent-filter> 
    <data android:scheme="http" android:host="twitter.com"/> 
    <action android:name="android.intent.action.VIEW" /> 
</intent-filter> 

然後,當用戶點擊一個鏈接,在瀏覽器中嘰嘰喳喳,他們將詢問完成操作需要使用什麼應用程序:瀏覽器或您的應用程序。

當然,如果你要提供你的網站和應用程序之間的緊密集成,您可以定義自己的方案:

<intent-filter> 
    <data android:scheme="my.special.scheme" /> 
    <action android:name="android.intent.action.VIEW" /> 
</intent-filter> 

然後,在你的web應用程序,你可以把喜歡的鏈接:

<a href="my.special.scheme://other/parameters/here">

而當用戶點擊它時,你的應用程序將自動啓動(因爲它可能是唯一可以處理my.special.scheme://類型的uris)。唯一的缺點是,如果用戶沒有安裝應用程序,他們會得到一個令人討厭的錯誤。我不確定有什麼方法可以檢查。

編輯:要回答你的問題,你可以使用getIntent()。getData()它返回一個Uri對象。然後可以使用Uri。*方法來提取所需的數據。例如,假設用戶點擊一個鏈接http://twitter.com/status/1234

strong textUri data = getIntent().getData(); 
String scheme = data.getScheme(); // "http" 
String host = data.getHost(); // "twitter.com" 
List<String> params = data.getPathSegments(); 
String first = params.get(0); // "status" 
String second = params.get(1); // "1234" 

你可以做上面的任何地方的活動,但你可能會想這樣做在的onCreate()。您還可以使用params.size()獲取路徑段的數量,即在Uri中我的路徑段數爲enter code here。查看javadoc或android開發人員網站,瞭解可用於提取特定部分的其他Uri方法。

Launch custom android application from android browser

+0

謝謝,但我不認爲這會幫助我。我不需要處理在瀏覽器中點擊的鏈接,我需要將文件從我的SD卡傳遞到活動(實際上,該文件的路徑將執行此操作)。當我將操作更改爲android.action.VIEW時,我的應用程序不再列在「共享通過」屏幕中。我的問題是,getIntent()。getData();返回null。 – Dusan

相關問題