用戶行為
用戶使用手機拍攝照片
用戶下載網頁上的照片,網盤的照片,微博的照片到手機
用戶導入照片到SD卡
需求
當用戶發生上述行為的時候,將增加的照片導入到程序並上傳
實現思路
監聽相機應用
如果用戶拍攝了照片,可能會觸發一個Intent,發送廣播通知給其他程序
public static final String ACTION_NEW_PICTURE
Added 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 {
@Override
public 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
優點
能夠監聽到上述的所有的用戶行為
缺點
需要硬編碼,並且監聽的目錄太多,事倍功半