Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

android - 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();
 }
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...