1

虽然活动可见,但我希望在从设备安装或删除媒体时通知它。不幸的是,我无法收到这些通知。我唯一能得到的是foo!我作为一个简单的测试创建的。

public class MyActivity extends AppCompatActivity {

  private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(ActivityFamily.class.getName(), intent.getAction());
    }
  };

  @Override
  protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter();
    filter.addAction("foo!");
    filter.addAction(Intent.ACTION_MEDIA_EJECT);
    filter.addAction(Intent.ACTION_MEDIA_REMOVED);
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
    registerReceiver(receiver, filter);

    // just added this as a test for "foo!" action
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, PendingIntent.getBroadcast(this, 0, new Intent().setAction("foo!"), 0));
  }

  @Override
  protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
  }
}

onReceive当我从设备中删除媒体时,为什么没有被调用?

我什至尝试创建一个全新的MyReceiver.java并在 中定义它AndroidManifest.xml,但这也不起作用。

<receiver android:name=".MyReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_EJECT" />
        <action android:name="android.intent.action.MEDIA_REMOVED" />
        <action android:name="android.intent.action.MEDIA_MOUNTED" />
        <action android:name="android.intent.action.MEDIA_BAD_REMOVAL" />
        <data android:scheme="file" />
    </intent-filter>
</receiver>
4

1 回答 1

3

我在这里找到了答案。我需要将该file:方案添加到意图过滤器中。

使用前registerReceiver添加filter.addDataScheme("file");

对于清单中注册的静态广播接收器,<data android:scheme="file" /><intent-filter>.

于 2016-02-12T16:08:51.170 回答