主要问题:我需要在屏幕截图发布后更新用户界面。
我尝试在MainActivity.java中以编程方式在onResume()中创建一个BroadcastReceiver,并且由于某种原因它没有获取截图。 所以,我尝试了在Manifest中声明的BroadcastReceiver,它正确地获取截图,但我无法更新UI。
在AndroidManifest.xml中定义的BroadcastReceiver作为Activity的内部类必须是静态的,否则我会收到此错误:java.lang.RuntimeException: Unable to instantiate receiver com.patmyron.blackbox.MainActivity$MyReceiver: java.lang.InstantiationException: java.lang.Class<com.patmyron.blackbox.MainActivity$MyReceiver> has no zero argument constructor
如果我尝试在MyReceiver中使用findViewById(),我会收到错误:
Non-static method 'findViewById(int)' cannot be referenced from a static context
以下是我目前的代码:
在AndroidManifest.xml中声明的BroadcastReceiver:
<receiver android:name=".MainActivity$MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.MEDIA_SCANNER_SCAN_FILE" />
<data android:scheme="file" />
</intent-filter>
</receiver>
MainActivity中的BroadcastReceiver类:
public static class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("this works", "SCREENSHOT");
// ((TextView) findViewById(R.id.tv13)).setText("SCREENSHOT");
}
}
答案 0 :(得分:0)
因此,当我尝试以编程方式在MainActivity.java中的onResume()中创建BroadcastReceiver时,我忘记了一个部分。
以下是完整的工作代码:
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.e("this works", "SCREENSHOT");
((TextView) findViewById(R.id.tv13)).setText("SCREENSHOT");
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
filter.addDataScheme("file");
registerReceiver(receiver, filter);
我错过了filter.addDataScheme("file");
行。