Synchronize of thread cause deadlock? - android

The same project runs perfect on Windows/iOS platform, but cause deadlock on Android (two different android devices) after running for uncertain duration.
procedure TTestThread.FSynProc;
begin
Inc(Form1.FExecuted); //Variable of TForm
Form1.Text1.Text:= IntToStr(Form1.FExecuted);
end;
procedure TTestThread.Execute;
var
begin
while not Self.Terminated do
begin
Self.Synchronize(FSynProc);
sleep(10);
end;
end;
constructor TTestThread.Create;
begin
inherited Create(True);
Self.FreeOnTerminate:= True;
end;
destructor TTestThread.Destroy;
begin
inherited;
end;
code for launch TTestThread
procedure TForm1.StartTTProc;
begin
ftt:= TTestThread.Create; // Variable of TForm
ftt.Start;
end;
After StartTTProc, the number shows in 'Text1' increase continusely.
After running for an uncertain duration on android device, App freezed.
any advice?

Related

TIdTCPClient app crash on android 6

On Delphi XE8 i have simple function to check internet connection:
function TForm1.Internet: boolean;
begin
result:=false;
try
IdTCPClient1.ReadTimeout:=2500;
IdTCPClient1.ConnectTimeout:=2500;
IdTCPClient1.Port:=80;
IdTCPClient1.Host:='google.pl';
IdTCPClient1.Connect;
IdTCPClient1.Disconnect;
result:=true;
except
result:=false;
end;
end;
Everything works just fine in older android version but in andoid 6 the app just crashes (close) when i call IdTCPClient1.Connect.
Then I learned that this is blocking function and it has to be in worker thread so i wrote something like this:
type
TTest = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
and in the implementation section:
procedure TThread.Execute;
begin
try
Form1.IdTCPClient1.ReadTimeout:=2500;
Form1.IdTCPClient1.ConnectTimeout:=2500;
Form1.IdTCPClient1.Port:=80;
Form1.IdTCPClient1.Host:='google.pl';
Form1.IdTCPClient1.Connect;
Form1.IdTCPClient1.Disconnect;
except
showmessage('no internet connection');
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Test : TTest;
begin
Test := TTest.Create(False);
end;
but unfortunately the app is still closing on android 6 when i call TForm1.Button1Click (on windows and older android versions works just fine)
Please help me ;)

Write into the SQLite database from an Android service in Delphi (RAD Studio)

I have an Android application and service in the same process. Write code under RAD Studio Delphi 10.1.
I need to get geographic coordinates in Android Service (that I'm doing well) and write them to the SQLite database.
And from time to time the application can (when the user needs) process the coordinates in the user interface.
When I put TConnection (any - ADO, FireDAC, UniDAC) into DataModule not even make an active connection, the service stops working, even not running the OnStartCommand event.
Monitor.bat shows no obvious errors.
Please tell me how to work with a SQLite database in Android Service and it Android Application at the same time.
I found a solution:
I updated UniDAC components for Berlin to latest version (6.3.12).
TUniConnection and TUniQuery well work with SQLite in Android Service.
Add to Project->Deployment of the host application my SQLite DB-file, Remote Path sets to ".\assets\internal\".
I hope this code will useful for you.
procedure TDM.conSQLiteBeforeConnect(Sender: TObject);
begin
{$IF DEFINED(iOS) or DEFINED(ANDROID)}
conSQLite.Database := TPath.Combine(TPath.GetDocumentsPath, 'mybase.sqlite');
{$ENDIF}
end;
procedure TDM.conSQLiteError(Sender: TObject; E: EDAError; var Fail: Boolean);
begin
Log('--- DB error: %s:', [E.Message]);
Fail := False;
end;
function TDM.AndroidServiceStartCommand(const Sender: TObject; const Intent: JIntent; Flags, StartId: Integer): Integer;
begin
Log('+ START with Intent: ' + JStringToString(Intent.getAction.toString), []);
if Intent.getAction.equalsIgnoreCase(StringToJString('StopIntent')) then
begin
try
conSQLite.Disconnect;
Log('- DB disconnected', []);
except
on E: Exception do
Log('- can not to disconnect DB', [E.Message]);
end;
Log('... service to be stoped', []);
JavaService.stopSelf;
Result := TJService.JavaClass.START_NOT_STICKY; // don't reload service
end
else
begin
Log('... service started', []);
try
conSQLite.Connect;
Log('+ DB connected', []);
UniQuery.SQL.Text := 'select count(*) as ALLREC from orders';
UniQuery.Open;
if UniQuery.RecordCount > 0 then
begin
UniQuery.First;
Log('... record count: %s', [UniQuery.FieldByName('ALLREC').AsString]);
end;
UniQuery.Close;
except
on E: Exception do
Log('- can not to connect DB: %s', [E.Message]);
end;
Result := TJService.JavaClass.START_STICKY; // rerun service if it stops
end;
end;
I have struggled the same issue but I started to use TSQLConnection (dbexpress) component with TSQLQuery (dbexpress) component and these are components wrok well in Android service.

Can Delphi Firemonkey TControl.MakeScreenshot work in a thread?

I've created a simple FireMonkey screenshot capture that works fine on Android and Windows..:
procedure Capture;
var
B : TBitmap;
begin
try
B := Layout1.MakeScreenshot;
try
B.SaveToFile( ..somefilepath.png );
finally
B.Free;
end;
except
on E:Exception do
ShowMessage( E.Message );
end;
end;
end;
when I moved it to a thread as below, it works fine in Windows but in Android I get the exception 'bitmap too big' from the call to MakeScreenshot. Are there additional steps needed to employ MakeScreenshot in a thread?
procedure ScreenCaptureUsingThread;
begin
TThread.CreateAnonymousThread(
procedure ()
var
B : TBitmap;
begin
try
B := Layout1.MakeScreenshot;
try
B.SaveToFile( '...somefilepath.png' );
finally
B.Free;
end;
except
on E:Exception do
TThread.Synchronize( nil,
procedure ()
begin
ShowMessage( E.Message );
end );
end).Start;
end;
Later addition. Based on suggestions by Sir Rufo and Sebastian Z, this solved the problem and allowed use of a thread:
procedure Capture;
begin
TThread.CreateAnonymousThread(
procedure ()
var
S : string;
B : TBitmap;
begin
try
// Make a file name and path for the screen shot
S := '...SomePathAndFilename.png';
try
// Take the screenshot
TThread.Synchronize( nil,
procedure ()
begin
B := Layout1.MakeScreenshot;
// Show an animation to indicate success
SomeAnimation.Start;
end );
B.SaveToFile( S );
finally
B.Free;
end;
except
on E:Exception do
begin
TThread.Synchronize( nil,
procedure ()
begin
ShowMessage( E.Message );
end );
end;
end;
end).Start;
end;
MakeScreenShot is not thread safe, so you cannot safely use it in a thread. If this works in Windows then I'd say you were just lucky. I'd suggest that you take the screenshot outside of the thread and only use the thread for saving the screenshot to png. Painting should be fast while encoding to png needs a lot more resources. So you should still benefit pretty much from the thread.

Delphi XE5 Android Thread makes app crash

I have a thread downloading and saving a clientDataset file cds file from a remote Datasnap Server.
This thread works in Windows, IOS (Simulator, Iphone, Ipad) but not on Android.
The app crashes after completed the file download and save it on Android.
The code is simple.
Thread:
TDownloadSaveRemoteDBThread = class (TThread)
public
Username,Password,host,port : String;
error : String;
Folder : String;
ServerMethod : String;
filename : String;
protected
procedure Execute; override;
end;
procedure TDownloadSaveRemoteDBThread.Execute;
var
sqlCon : TSqlConnection;
cds : TClientDataset;
ssm : TSqlServerMethod;
dpr : TDataSetProvider;
begin
inherited;
error :='';
SqlCon:=TSQLConnection.Create(nil);
try
sqlCon.DriverName:='Datasnap';
sqlCon.LoginPrompt:=false;
sqlCon.Params.Values['hostname']:=host;
sqlCon.Params.Values['port']:=port;
sqlCon.Params.Values['UserName']:=Username;
sqlCon.Params.Values['Password']:=Password;
try
sqlCon.Open;
cds:=TClientDataset.Create(nil);
ssm:=TSqlServerMethod.Create(nil);
dpr:=TDataSetProvider.Create(nil);
try
ssm.SQLConnection:=SqlCon;
ssm.ServerMethodName:=ServerMethod;
dpr.DataSet:=ssm;
cds.SetProvider(dpr);
cds.Open;
cds.SaveToFile(folder+filename);
cds.Close;
finally
cds.free;
ssm.free;
dpr.free;
end;
Except
on E : Exception do
Begin
error:=E.Message;
SQLCon.Close;
End;
end;
finally
SQLCon.Close;
SQLCon.free;
end;
end;
I have a button to start the thread in my mainform “Start Form”
procedure TStartForm.Button1Click(Sender: TObject);
var
DownloadSaveRemoteDBThread : TDownloadSaveRemoteDBThread;
begin
DownloadSaveRemoteDBThread:= TDownloadSaveRemoteDBThread.Create(true);
DownloadSaveRemoteDBThread.OnTerminate:= StartForm.ferdigHentDB;
DownloadSaveRemoteDBThread.Password:='test';
DownloadSaveRemoteDBThread.Username:='test';
DownloadSaveRemoteDBThread.host:=edit1.text; //127.0.0.1
DownloadSaveRemoteDBThread.port:='211';
DownloadSaveRemoteDBThread.Folder:=System.IOUtils.TPath.GetDocumentsPath + PathDelim +'db'+ PathDelim;
DownloadSaveRemoteDBThread.ServerMethod:= 'TServerMethods2.hentselect3';
DownloadSaveRemoteDBThread.filename:='select3.cds';
DownloadSaveRemoteDBThread.FreeOnTerminate:=true;
DownloadSaveRemoteDBThread.Start;
end;
Then after thread is finished I have this simple procedure
procedure TStartForm.ferdigHentDB(sender: Tobject);
begin
with sender as TDownloadSaveRemoteDBThread do
Begin
if error > '' then
Begin
showmessage(error);
End;
End;
end;
Any suggestions why Android crashes, is there an easy fix for this issue?
TThread in XE5 has two major bugs on Android. Sychronize() and Queue() are broken (Synchronize() is used to trigger the OnTerminate event), and TThread does not detach itself from the Android JVM before termination if any JNI objects are used by the thread. The first bug has not been fixed yet. The second bug is fixed in XE6, but there is a workaround you can use in XE5.

Delphi xe5 Android app freezes when accessing Clipboard

I am building an application for Android using Delphi XE5 that makes use of the Zxing barcode application and it uses the clipboard to retrieve the result. All of the code (Most of it anyway) is from a tutorial that I have found on the web. When I followed the tutorial, it worked to a charm but when applying the SAME code within an application that I was already working on - it did not work. Whenever accessing the clipboard ( in the 'OnTimer' event), the application always hangs and stops working. No error, nothing. App freezes and I have to close it via the phone's task manager.
The application fails right after the following line
Log.Add('AndroidClipboardScanner:1'); Log.SaveToFile(INIFileLog);
I have changed the coding around so that the app assumed the Clipboard service was available in the Ontimer event and it proceeded but it then failed after the following line:
Log.Add('AndroidClipboardScanner:4'); Log.SaveToFile(INIFileLog);
I am not sure where to begin debugging because the same code works in the other application that I created following the initial guide I found. I can also confirm that the ClipService is being assigned properly, otherwise the intent wouldn't even begin. Any help or guidance would be much appreciated ! Below is my code...
This Declared in the 'Private' variables section of the form:
ClipService: IFMXClipboardService;
This within the 'OnTimer' event for Timer1:
procedure TMain_Form.Timer1Timer(Sender: TObject);
var
barCode : String;
begin
timer1.Enabled := false;
Log.Add('AndroidClipboardScanner:0.1'); Log.SaveToFile(INIFileLog);
Try
if assigned(ClipService) then begin
Log.Add('AndroidClipboardScanner:1'); Log.SaveToFile(INIFileLog);
if (ClipService.GetClipboard.ToString <> 'nil') then
begin
Log.Add('AndroidClipboardScanner:2'); Log.SaveToFile(INIFileLog);
timer1.Enabled := false;
Log.Add('AndroidClipboardScanner:3'); Log.SaveToFile(INIFileLog);
Elapsed := 0;
Log.Add('AndroidClipboardScanner:4'); Log.SaveToFile(INIFileLog);
editHold.PasteFromClipboard;
//EditHold.Text := ClipService.GetClipboard.ToString;
Log.Add('AndroidClipboardScanner:5'); Log.SaveToFile(INIFileLog);
end else
begin
Log.Add('AndroidClipboardScanner:6'); Log.SaveToFile(INIFileLog);
Timer1.Enabled := False;
Log.Add('AndroidClipboardScanner:7'); Log.SaveToFile(INIFileLog);
end;
Log.Add('AndroidClipboardScanner:8'); Log.SaveToFile(INIFileLog);
end else begin
ShowMessage('Unexpected error has occured');
end;
Except
ShowMessage('Unexpected error has occured..');
End;
end;
Within the ONCreate procedure of the form:
if not TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService,
IInterface(ClipService)) then begin
ShowMessage('Clipboard Failed:1');
ClipService := nil;
end;
Elapsed := 0;
This is for click event for the button that begins the intent:
procedure TMain_Form.Button_ShowScannerClick(Sender: TObject);
{$IFDEF ANDROID}
var
intent: JIntent; {$ENDIF}
begin
{$IFDEF ANDROID}
//ShowMessage('Scanner:1');
if assigned(ClipService) then begin
//ShowMessage('Scanner:2');
ClipService.SetClipboard('nil');
intent := tjintent.Create;
intent.setAction(stringtojstring('com.google.zxing.client.android.SCAN'));
intent.putExtra(tjintent.JavaClass.EXTRA_INTENT,
stringtojstring('"SCAN_MODE"'));
sharedactivity.startActivityForResult(intent,0);
Elapsed := 0;
timer1.Enabled := true;
//ShowMessage('Scanner:3');
end;
{$ENDIF}
You didn't set the SCAN_MODE parameters like:
intent.putExtra(tjintent.JavaClass.EXTRA_TEXT,
stringtojstring('"SCAN_MODE","ONE_D_MODE,QR_CODE_MODE,PRODUCT_MODE,DATA_MATRIX_MODE"'));
Also you can check timer interval parameter...
I tested the solution on few devices.
With low interval value I had black screen sometimes

Categories

Resources