In Android, the intent message can be obtained by implementing the Broadcastreceiver interface with Java. However, Delphi program can not directly implement Jbroadcastreceiver, how can realize similar Java broadcastreceiver function?
Fortunately, Delphi provides the Tjfmxbroadcastreceiver class with the broadcastreceiver, and we can do it for this purpose.
The following program fragment provides an example of how to obtain a USB peripheral unplugged message under Delphi.
usessystem.sysutils, System.classes, System.Generics.Collections, Androidapi.JNI.USB, Androidapi.JNI.Embarcadero, Androidapi.jnibridge, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes, ANDROIDAPI.JNI.APP, Androidapi.JNI.os,...; Tusbftdibroadcastreceiverlistener=class(tjavalocal, Jfmxbroadcastreceiverlistener)Private[Weak] fport:tftdiport; Public ConstructorCreate (Constowner:tftdiport); procedureOnReceive (context:jcontext; intent:jintent);cdecl; End; Tftdiport=class(Tinterfacedobject, Icommport)protected class varFmanager:jd2xxmanager; class varFlistener:tusbftdibroadcastreceiverlistener; class varFreceiver:jfmxbroadcastreceiver; class varFusbmanager:jusbmanager; class varFfilter:jintentfilter; class procedureInitclass; Public functionConnect (device:string): Boolean; procedureDisconnect; ...... End;{Tusbftdibroadcastreceiverlistener}Constaction_usb_permission='Com.android.example.USB_PERMISSION';ConstructorTusbftdibroadcastreceiverlistener.create (Constowner:tftdiport);begin inheritedCreate; FPort:=Owner;End;proceduretusbftdibroadcastreceiverlistener.onreceive (Context:jcontext; intent:jintent);varaction:string; Accessory:jusbaccessory;beginAction:=jstringtostring (intent.getaction); ifAction=action_usb_permission Then begin if(Intent.getbooleanextra (TJUsbManager.JavaClass.EXTRA_PERMISSION_GRANTED, False)) Then beginAccessory:=Tjusbaccessory.wrap (Intent.getparcelableextra (TJUsbManager.JavaClass.EXTRA_ACCESSORY)); ifJstringtostring (Accessory.getmanufacturer) ='FTDI' Then beginFport.connect (jstringtostring (accessory.tostring)); End; End; End Else if(action=tjusbmanager_action_usb_device_detached) Then beginFport.disconnect; End Else begin End;End;class procedureTftdiport.initclass;beginif notAssigned (Fusbmanager) Then beginFusbmanager:=Tjusbmanager.wrap (Sharedactivitycontext.getsystemservice (TJContext.JavaClass.USB_SERVICE)); if notAssigned (Fusbmanager) ThenExit; Flistener:= Tusbftdibroadcastreceiverlistener.create (Nil); if notAssigned (Flistener) ThenExit; Freceiver:=TJFMXBroadcastReceiver.JavaClass.init (Flistener); if notAssigned (Freceiver) ThenExit; Ffilter:=TJIntentFilter.JavaClass.init (stringtojstring (action_usb_permission)); if notAssigned (Ffilter) ThenExit; Ffilter.addaction (TJUsbManager.JavaClass.ACTION_USB_ACCESSORY_DETACHED); Sharedactivitycontext.registerreceiver (Freceiver, Ffilter); End;End;
Delphi implements Broadcastreceiver functions under Android (for example, obtaining USB Peripheral Unplugged messages under Delphi)