我正在尝试制作一个可以检测用户何时拍照的应用。我设置了一个广播接收器类并通过以下方式将其注册到 list 文件中:
<receiver android:name="photoReceiver" >
<intent-filter>
<action android:name="com.android.camera.NEW_PICTURE"/>
<data android:mimeType="image/*"/>
</intent-filter>
</receiver>
无论我尝试做什么,程序都不会收到广播。这是我的接收器类:
public class photoReceiver extends BroadcastReceiver {
private static final String TAG = "photoReceiver";
@Override
public void onReceive(Context context, Intent intent) {
CharSequence text = "caught it";
int duration = Toast.LENGTH_LONG;
Log.d(TAG, "Received new photo");
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
如果我在 list 和 Activity 中删除 mimeType 行,我会使用发送自己的广播
Intent intent = new Intent("com.android.camera.NEW_PICTURE");
sendBroadcast(intent);
然后我成功接收到广播并且可以看到日志和 toast 窗口。我以正确的方式接近这个吗?有什么需要补充的吗?
最佳答案
我解决了这个问题,但使用了不同的方法。我没有使用广播接收器,而是在相机保存到的单独文件夹上设置了一个文件观察器。它不像其他方式那样实用,但它仍然可以正常工作。以下是我的设置方式:
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
关于android - 广播接收器不会收到相机事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4571461/