这次,这是在Delphi 10 Seattle中实现广播接收器的一种方法。
这比您想像的要容易。
创建一个类以接收通知。
uses
Androidapi.JNIBridge,
Androidapi.JNI.Embarcadero,
Androidapi.JNI.GraphicsContentViewText;
type
TMyReceiver = class(TJavaLocal, JFMXBroadcastReceiverListener)
public
constructor Create;
procedure onReceive(context: JContext; intent: JIntent); cdecl;
end;
uses
Androidapi.Helpers,
Androidapi.JNI.JavaTypes;
{ TMyReceiver }
constructor TMyReceiver.Create;
begin
inherited;
end;
procedure TMyReceiver.onReceive(context: JContext; intent: JIntent);
begin
Log.d('Broadcast Received = ' + JStringToString(intent.getAction));
end;
设置为在表单的OnCreate事件中接收通知,并在OnDestroy事件中释放通知。
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ private 宣言 }
FMyListener: TMyReceiver;
FBroadcastReceiver: JFMXBroadcastReceiver;
public
{ public 宣言 }
end;
procedure TForm1.FormCreate(Sender: TObject);
var
Filter: JIntentFilter;
begin
FMyListener := TMyReceiver.Create;
FBroadcastReceiver := TJFMXBroadcastReceiver.JavaClass.init(FMyListener);
Filter := TJIntentFilter.JavaClass.init;
Filter.addAction(TJIntent.JavaClass.ACTION_SCREEN_OFF);
Filter.addAction(TJIntent.JavaClass.ACTION_SCREEN_ON);
TAndroidHelper.context.getApplicationContext.registerReceiver
(FBroadcastReceiver, Filter);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
TAndroidHelper.context.getApplicationContext.unregisterReceiver
(FBroadcastReceiver);
end;
以上是完成。
当执行该应用程序并打开/关闭屏幕时,将在日志中输出以下内容。
FMX: BroadcastSample: Broadcast Received = android.intent.action.SCREEN_OFF
FMX: BroadcastSample: Broadcast Received = android.intent.action.SCREEN_ON