Search code examples
javaandroidbroadcastreceiverscreenshot

Update UI from BroadcastReceiver after screenshot


I need to update the UI after a screenshot occurs.

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.

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

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:

BroadcastReceiver declared in AndroidManifest.xml:

    <receiver android:name=".MainActivity$MyReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_SCANNER_SCAN_FILE" />
            <data android:scheme="file" />
        </intent-filter>
    </receiver>

BroadcastReceiver class within MainActivity:

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

Solution

  • I forgot a part when attempting to programmatically create a BroadcastReceiver in onResume() in MainActivity.java.

    Here is the full working code:

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

    I was just missing the filter.addDataScheme("file"); line.