2012-09-12 205 views
1

我們有一個將圖像打印到藍牙打印機的應用程序。此應用程序在Android 4.0 ICS上運行良好,但是當我們將其中一個升級到Android 4.1 jelly bean時,此打印在logcat中停止工作:Android藍牙打印停止工作4.1

W/System.err(19319):java.lang。拋出:SecurityException:權限拒絕: 寫入com.android.bluetooth.opp.BluetoothOppProvider URI 內容://com.android.bluetooth.opp/btopp從PID = 19319,UID = 10106 需要android.permission.ACCESS_BLUETOOTH_SHARE,或 grantUriPermission ()

問題是我們正在聲明該權限,所以這個錯誤使得n o感覺到我們。以下是我們清單中的行

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.turner.itstrategy.LumenboxClient" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk android:minSdkVersion="11" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WAKE_LOCK" /> 
    <uses-permission android:name="android.permission.ACCESS_BLUETOOTH_SHARE"/> 
    <uses-permission android:name="android.permission.BLUETOOTH"/> 
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
    <uses-permission android:name="android.permission.VIBRATE" /> 

    (stuff removed) 
</manifest> 

這是我們用來打印的代碼。這段代碼是從stackoverflow和其他地方的例子中提取的。

ContentValues values = new ContentValues(); 

String path = Environment.getExternalStorageDirectory().toString(); 
File imageFile = new File(path, "CurrentLumenboxPrint.jpg"); 

//build the message to send on BT 
values.put(BluetoothShare.URI, Uri.fromFile(imageFile).toString()); 
values.put(BluetoothShare.MIMETYPE, "image/jpeg"); 
values.put(BluetoothShare.DESTINATION, device.getAddress()); 
values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND); 
Long ts = System.currentTimeMillis(); 
values.put(BluetoothShare.TIMESTAMP, ts); 

// Here is where the exception happens  
final Uri contentUri = getApplicationContext().getContentResolver().insert(BluetoothShare.CONTENT_URI, values); 

現在我們死在水中..任何建議讚賞。

+0

我也有同樣的問題,使用果凍豆藍牙。 – Giuseppe

+0

此代碼在2.3.8以下無法運行,請幫助我嗎?當我使用這個代碼,並嘗試發送文件時,它什麼也沒有顯示。我檢查使用斷點,它只是從所有行傳遞沒有任何反應。在2.3.8中它正在工作。 @grennis –

+0

發佈的代碼並不適用於任何地方。使用下面答案中發佈的方法。 –

回答

5

發現這將不再適用於4.1。直接寫入內容提供商的權限現在受「簽名」保護,這意味着您必須使用用於簽署藍牙應用程序的相同密鑰簽署您的應用程序。

所以這裏是我們如何做到這一點。首先使用共享意圖直接發送到應用程序:

Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
sharingIntent.setType("image/jpeg"); 
sharingIntent.setComponent(new ComponentName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity")); 
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile)); 
startActivity(sharingIntent); 

這有效,但它彈出「選擇設備」的用戶界面。如果你不希望你必須處理意圖android.bluetooth.devicepicker.action.LAUNCH並用廣播消息android.bluetooth.devicepicker.action.DEVICE_SELECTED迴應。但用戶仍然可以獲得選擇器彈出窗口。

UPDATE:我寫了一個blog post以及如何做到這一點的完整說明。

+0

對此很好的回答+1。但是,你能告訴我如何使用這種方法分享其他媒體嗎? @grennis –

+0

有用,但您對選擇設備用戶界面的不可預測性質是正確的。非常令人沮喪的是,他們增加了這個藍色(牙齒),並沒有明顯的原因。 –

+0

你能提供一個代碼樣本來處理LAUNCH意圖並用廣播DEVICE_SELECTED進行響應嗎? – tuxGurl