即使没有用户活动,我也想保持设备开启并避免从内存中卸载我的应用程序。服务之类的。我制作了如何检查网络在 Android 和 iOS 上是否可用(Delphi XE5)之类的模块,但是当我运行 SetWakeLock 时系统崩溃:
unit Android.PowerManager;
interface
function SetWakeLock : boolean;
procedure ReleaseWakeLock;
implementation
uses
System.SysUtils,
Androidapi.JNI,
Androidapi.JNIBridge,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes,
FMX.Helpers.Android;
type
JPowerManager = interface;
JWakeLock = interface;
JWakeLockClass = interface(JObjectClass)
['{4CF7A13D-15A9-4DEE-8CA7-66600C188CB7}']
end;
[JavaSignature('android/os/PowerManager/WakeLock')]
JWakeLock = interface(JObject)
['{55983EDC-782F-490A-BF0C-12207EB7829E}']
{Methods}
procedure acquire; cdecl;
procedure release; cdecl;
function isHeld: Boolean; cdecl;
end;
TJWakeLock = class(TJavaGenericImport<JWakeLockClass, JWakeLock>) end;
JPowerManagerClass = interface(JObjectClass)
['{B127DD4E-1DA6-49E7-98BA-5966DC7E26FA}']
end;
[JavaSignature('android/os/PowerManager')]
JPowerManager = interface(JObject)
['{241C3B3D-3DF0-489B-A33E-3CD7F5D26313}']
{Methods}
function newWakeLock(levelAndFlags: integer; tag: JString): JWakeLock; cdecl;
end;
TJPowerManager = class(TJavaGenericImport<JPowerManagerClass, JPowerManager>) end;
function GetPowerManager: JPowerManager;
var
PowerServiceNative: JObject;
begin
PowerServiceNative := SharedActivityContext.getSystemService(TJContext.JavaClass.POWER_SERVICE);
if not Assigned(PowerServiceNative) then
raise Exception.Create('Could not locate Power Service');
Result := TJPowerManager.Wrap(
(PowerServiceNative as ILocalObject).GetObjectID);
if not Assigned(Result) then
raise Exception.Create('Could not access Power Manager');
end;
var fWakeLock : JWakeLock = nil;
function SetWakeLock : boolean;
var
PowerManager: JPowerManager;
begin
result := fWakeLock<>nil;
if result then begin
PowerManager := GetPowerManager;
fWakeLock := PowerManager.newWakeLock(1,StringToJString('VC')); //PARTIAL_WAKE_LOCK =1
Result := fWakeLock<>nil;
if Result then begin
fWakeLock.acquire;
Result := fWakeLock.IsHeld;
end;
end else if not fWakeLock.IsHeld then
fWakeLock.acquire;
end;
procedure ReleaseWakeLock;
begin
if fWakeLock<>nil then begin
fWakeLock.release;
end;
end;
end.