Android Intent BroadcastReceiver Example

Viewed 27

I am using a Zebra Android Scan-Gun and need to capture the hard-keyboard (not soft) keystrokes for P1, P2, F1, F2, etc... keys. Since Maui doesn't have events for KeyUp/KeyDown/KeyPressed there is nothing to inform me of a special keys being pressed. Not to mention I also have to put an Entry field on screens where there are only buttons because you can't catch a TextChanged event without an Entry.

My current solution involves Zebra StageNow to remap the P1 key to the "+" key and then strip it out of the Entry/TextBox (which is not a very elegant solution)

What I'm trying now is using the Windows app Zebra StageNow in Admin mode to remap the F11 key to send an Intent, OnKeyUp, Broadcast as seen in this screenshot.

Zebra StageNow Screenshot

Then I generate the bar-codes to program the scan-gun.

In the Android Scan-gun I then run StageNow and scan the bar-codes which programs the F11 key.

Then within my android app I added a class in the Platforms\Android folder called SpecialKeypress.cs

namespace myapp.Platforms.Android
{

    [BroadcastReceiver(Enabled = true, Exported = true)]
    [IntentFilter(new[] { "com.mycompany.myapp.F11" })]

    public class SpecialKeypress : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            var value = intent.GetStringExtra("Key"); // <-- I set a breakpoint here
            throw new NotImplementedException();
        }
    }
}

Then I added the following to my AndroidManifest.xml

    <application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true">
    
    <activity android:exported="true" android:name="com.mycompany.myapp.F11" >
      <intent-filter>
        <action android:name="com.mycompany.myapp.F11" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
      </intent-filter>
    </activity>
    
  </application>

I debug the app on the device and press F11 but alas my breakpoint is not hit in the OnReceive function.

I expect I'm missing something fundamental but I tried to keep it as simple as possible for this example. Also, there are no good examples of how to do this with Maui on the internet (yet).

1 Answers

You may need to register a receiver in your AndroidManifest.xml, and put some intent filters that define what type of messages this receiver will get. For example:

<receiver android:name=".SpecialKeypress">
<intent-filter> 
    <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
</intent-filter>
</receiver> 
Related