广播接收器android,Delphi 10中实现Android的广播接收器

这次,这是在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值