Watch, Follow, &
Connect with Us

For forums, blogs and more please visit our
Developer Tools Community.


Welcome, Guest
Guest Settings
Help

Thread: XE10 - Starting and Stopping a Service from within the app



Permlink Replies: 0
Wesley Harrison

Posts: 11
Registered: 6/5/11
XE10 - Starting and Stopping a Service from within the app
Click to report abuse...   Click to reply to this thread Reply
  Posted: Dec 22, 2017 3:32 AM
Seasons Greetings!

I have a standard app that is starting a service running on the device. This works fine. But my code to stop the same service is not working. I have tried a few different methods of starting/stopping, but no luck so far with stopping it.

Please see 3 functions below

StartService - working ok
StopService - not working
RunService(bStart) - This starts the service ok but does not stop the service

function StartService:boolean;
var
Intent: JIntent;
ResolveInfo: JResolveInfo;
begin
try

Intent := TJIntent.JavaClass.init(StringToJString('android.intent.main.MainActivity'));
Intent.setPackage(StringToJString('com.myservice'));

ResolveInfo := SharedActivity.getPackageManager.resolveActivity(Intent, 0);
Result := ResolveInfo <> nil;
if Result then
begin
SharedActivity.startActivity(Intent);
Toast('Service started ok', ShortToast);
end
else
Toast('Cannot start service', ShortToast);
except on e:exception do
Toast('Error in StartService',LongToast);
end;
end;

function StopService:Boolean;
var
Intent: JIntent;
ResolveInfo: JResolveInfo;
begin
try

Intent := TJIntent.JavaClass.init(StringToJString('android.intent.main.MainActivity'));
Intent.setPackage(StringToJString('com.myservice'));

ResolveInfo := SharedActivity.getPackageManager.resolveActivity(Intent, 0);
Result := ResolveInfo <> nil;
if Result then
begin
if SharedActivity.stopService(Intent) then
Toast('Service stopped ok', ShortToast);

// SharedActivity.stopLockTask; //does nothing
// SharedActivity.finishActivity(0); //does nothing
// SharedActivity.finish; //Closes this app

end;
except on e:exception do
Toast('Error in StopService',LongToast);
end;
end;


I tired the function below also, this starts the service but does not stop the service

procedure RunService(bStart:boolean);
var
LIntent: JIntent;
begin
LIntent := TAndroidHelper.Context.getPackageManager.getLaunchIntentForPackage(StringToJString('com.myservice'));
if LIntent <> nil then
begin
if bStart then
begin
Toast('Attempting to start...',LongToast);
TAndroidHelper.Context.startActivity(LIntent);
end
else
begin
Toast('Attempting to stop...',LongToast);
TAndroidHelper.Context.stopService(LIntent);
end;
end;
end;

Regards,
Wesley

Legend
Helpful Answer (5 pts)
Correct Answer (10 pts)

Server Response from: ETNAJIVE02