截图后如何从BroadcastReceiver更新UI [英] How to update UI from BroadcastReceiver after screenshot

查看:112
本文介绍了截图后如何从BroadcastReceiver更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主要问题:出现屏幕截图后,我需要更新UI。

我尝试以编程方式在onResume()中创建BroadcastReceiver MainActivity.java,由于某种原因,它没有拾取屏幕截图。
因此,我尝试了在清单中声明的​​BroadcastReceiver,它可以正确获取屏幕截图,但是我无法更新UI。

I tried programmatically creating a BroadcastReceiver in onResume() in MainActivity.java and it is not picking up screenshots for some reason. So, I tried a BroadcastReceiver declared in the Manifest and it picks up screenshots correctly, but I cannot update the UI.

在AndroidManifest.xml中定义的BroadcastReceiver为内部类的Activity必须是静态的,否则会出现此错误:

BroadcastReceiver defined in AndroidManifest.xml as inner class of Activity must be static or I get this error:

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(),则会收到错误消息:

If I try to use findViewById() inside of MyReceiver, I get the error:

Non-static method 'findViewById(int)' cannot be referenced from a static context

这是我当前拥有的代码:

Here is the code I have currently:

在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");
    }
}


推荐答案

所以,事实证明,尝试在MainActivity.java中的onResume()中以编程方式创建BroadcastReceiver时,我忘记了一部分。

So, it turns out I forgot a part when attempting to programmatically create a BroadcastReceiver in onResume() in MainActivity.java.

以下是完整的工作代码:

    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); 行。

这篇关于截图后如何从BroadcastReceiver更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆