广播接收器将不会接收摄像头事件 [英] broadcast receiver won't receive camera event
问题描述
我正在尝试开发一个可检测用户何时拍照的应用程序.我设置了广播接收器类,并通过以下方式将其注册到清单文件中:
I'm trying to make an app that detects when a user takes a photo. I set up a broadcast receiver class and registered it in the manifest file by:
<receiver android:name="photoReceiver" >
<intent-filter>
<action android:name="com.android.camera.NEW_PICTURE"/>
<data android:mimeType="image/*"/>
</intent-filter>
</receiver>
无论我做什么,该程序都不会收到广播.这是我的接收器类:
No matter what I try to do the program won't receive the broadcast. Here is my receiver class:
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();
}
}
如果我删除清单中的mimeType行,并且在我的活动中,我将使用发送自己的广播
If I remove the mimeType line in the manifest and in my activity I send my own broadcast using
Intent intent = new Intent("com.android.camera.NEW_PICTURE");
sendBroadcast(intent);
然后我成功接收了广播,并可以看到日志和吐司窗口.我是否以正确的方式来对待?我有什么需要补充的吗?
then I successfully receive the broadcast and can see the log and toast window. Am I approaching this the right way? Is there any thing that I need to add?
推荐答案
我通过使用其他方法解决了这个问题.我没有使用广播接收器,而是在相机保存到的单独文件夹中设置了文件观察器.它不像其他方法那样实用,但是仍然可以正常工作.这是我的设置方式:
I solved this but by using a different method. Instead of using a broadcast receiver I set up a fileobserver on separate folders that the camera saved to. It's not as practical as the other way, but it still works fine. Here's how I set it up:
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
这篇关于广播接收器将不会接收摄像头事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!