android - 广播接收器不会收到相机事件

标签 android android-manifest android-camera android-camera-intent

我正在尝试制作一个可以检测用户何时拍照的应用。我设置了一个广播接收器类并通过以下方式将其注册到 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/

相关文章:

java - 为什么不调用改造 validator ?

android - 找不到与给定名称匹配的资源(在 'icon' 处,值为 '@mipmap/ic_launcher.png' )

Android 深度链接两个单独的 Activity

android - 如何避免在图库中保存图片或在 Android 中自动删除图片?

android - zxing条码扫描仪自动对焦不起作用

android - 如何通过libyuv将NV21格式的android相机预览数据转换为i420?

Android:如何实现小区切换的监听器?

java - 试图让 static void 在所有类中可用?

java - 将 JSON 数据填充到 ListView

Android:安装APK后,打开按钮被禁用