Android 匯入手機圖片
使用者行為使用者使用手機拍攝照片使用者下載網頁上的照片,網盤的照片,微博的照片到手機使用者匯入照片到SD卡需求當使用者發生上述行為的時候,將增加的照片匯入到程式並上傳實現思路監聽相機應用如果使用者拍攝了照片,可能會觸發一個Intent,發送廣播通知給其他程式 public static final String ACTION_NEW_PICTUREAdded in API level 14 Broadcast Action: A new picture is taken by the camera, and the entry of the picture has been added to the media store. getData() is URI of the picture. Constant Value: "android.hardware.action.NEW_PICTURE" public static final String ACTION_NEW_VIDEO Added in API level 14 Broadcast Action: A new video is recorded by the camera, and the entry of the video has been added to the media store. getData() is URI of the video. Constant Value: "android.hardware.action.NEW_VIDEO" 代碼public class CameraEventReciver extends BroadcastReceiver { @Overridepublic void onReceive(Context context, Intent intent) { Cursor cursor = context.getContentResolver().query(intent.getData(),null,null, null, null); cursor.moveToFirst(); String image_path = cursor.getString(cursor.getColumnIndex("_data")); Toast.makeText(context, "New Photo is Saved as : -" + image_path, 1000).show(); }} <receiver android:name="sample.grass.category.mediastore.CameraEventReciver" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="android.hardware.action.NEW_PICTURE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </receiver>測試結果:能夠監聽到使用者拍攝了照片,但是僅限於系統相機,使用其他的相機apk可能收到廣播,也有可能收不到 優點即使應用程式沒有啟動,也能接收到通知,從而被喚醒缺點有的相機應用並沒有實現發送廣播,不是完全可以被依賴無法監測使用者下載圖片或者匯入照片監聽Meida資料庫無論是使用者使用哪個相機拍攝照片,還是使用者匯入圖片到sd卡,還是使用者下載照片到手機,都會引起Media 資料庫的變化,監聽這個變化,匯入照片到Trunx 代碼class UriObserver extends ContentObserver { public UriObserver(Handler handler) { super(handler); // TODO Auto-generated constructor stub } @Override public void onChange(boolean selfChange) { // TODO Auto-generated method stub super.onChange(selfChange); Log.d("INSTANT", "GETTING CHANGES"); }}UriObserver observer = new UriObserver(new Handler());this.getApplicationContext() .getContentResolver() .registerContentObserver( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, false, observer);優點可以監聽使用者匯入圖片,使用者下載圖片,使用者使用各種第三方相機拍攝圖片缺點依賴於程式被啟動,如果程式被殺掉了,就無法監聽了監聽檔案目錄代碼FileObserver observer = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/100MEDIA") { // set up a file observer to watch this directory on sd card @Override public void onEvent(int event, String file) { if(event == FileObserver.CREATE && !file.equals(".probe")){ // check if its a "create" and not equal to .probe because thats created every time camera is launched Log.d(TAG, "File created [" + android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/100MEDIA/" + file + "]"); fileSaved = "New photo Saved: " + file; } } };observer.startWatching(); // start the observer優點能夠監聽到上述的所有的使用者行為缺點需要寫入程式碼,並且監聽的目錄太多,事倍功半