[英] Delphi 编写 Android 服务

原文链接:http://blog.blong.com/2013/11/delphi-and-android-services-part-2.html(国外)

原文标题:Delphi 和 Android 服务

注:本来想翻译给大家,但感觉我这英语太差,实在无法精准的将老外的这篇文章翻译出来,所以原文输出吧。谁要是能翻译的不错,请联系我,我会将您的翻译放出来。

第一部分:

Delphi and Android services

Since Delphi’s introduction of Android support with the release of XE5, there have been many questions posted hither and thither regarding whether and how you can build service applications with it. The pervading suggestion or suspicion is that maybe Delphi isn’t cut out to build such exotic Android creations.

Well, if your goal is to just build some sort of a service app I wouldn’t particularly recommend Delphi for the job right now, simply because it hasn’t got the wherewithal to support you in that endeavour in its current guise, and consequently it’s quite difficult. Really, if you just want to build a service app you’d probably have an easier time using Java or Oxygene for Java in conjunction with the Android SDK.

However if you are invested in building a Delphi Android app, are in the midst of building a FireMonkey application for mobile deployment, and need an Android service as part of that, well it’s quite possible. But as I may have mentioned, it’s neither particularly easy nor especially straightforward.

I am aware that I have (at this time of writing) yet to write up the business of adding Android menus to Delphi apps, employing a splash screen and launching Android activities and getting results back (as demo’d in my CodeRage 8 talk, albeit with code samples available in that linked post)*.

Now I can add to the list of things I have yet to write up the steps for creating a service application. If you take a look at this Google Play Store listing you’ll see I’ve built an app that, as well as a splash screen, also implements a service.

ServiceApp_thumb ServiceAppProcess_thumb

So yes, it’s quite feasible to build a service and a broadcast receiver in a Delphi app. That said, I’ve had to be a little creative on exiting the app to avoid a failure being evident on the screen.

As mentioned, these Android aspects that fall outside the standard simple business app paradigm haven’t factored into what is readily supported currently in Delphi’s Android support. Hopefully this will be improved as time goes on to allow all sorts of Android features and facets to be surfaced in Delphi Android code. In the mean time a certain degree of spelunking and skulduggery is needed to achieve certain ends.

I know quite a few people are clamouring for knowledge on how to build service apps. Hopefully in the near future I’ll write it up, but certainly in the nearer future I’ll release the code sample, once I’ve exhausted possibilities to clean up the wrinkle around app shutdown. That should satisfy the keener of you out there. In the mean time, be satisfied that it’s been proved to be possible at all.

【第二部分】

It’s been a while now since I posted up the link to my Delphi service example on Google Play.

I mentioned at the time that it was not a trivial exercise and was somewhat imperfect in implementation (although I’d done my best to disguise this fact). Indeed you only really see an issue if you are looking at the logcat output from the app (either using the command-line adb logcat command, or using the deprecated DDMS tool or the replacement Monitor tool). Alas the app dies while endeavouring to tidy up for exit…

I also mentioned at the time that I was hoping to work out some scheme to remedy the situation before releasing the example source, something to do with pride or perfectionism or some such… Anyway, with the day job, the evening job, the prep work for last week’sBe-Delphi 3.0 event in Belgium my plans haven’t been accomplished and I have still to work out if it’s feasible to clean up the shutdown part of the sample. All my current efforts have come to little in resolving it.

So, given that there have been a number of requests for the source I have now made it available at this download link. This is the same as the sample online other than it has no splash screen. This example is free of a splash screen to simplify the example and leave it clearer. There are a couple of examples that incorporate a splash screen and have similar custom build steps available in my CodeRage 8 session files.

Please note that the archive has a Readme file in it, and you should take the time to read through this file carefully as it explains the non-standard build steps required to get the sample successfully built for deployment. If you don’t follow the Readme file, then you’re unlikely to get any joy with the sample at all.

For your convenience I include the text of the ReadMe file below.

As you will see, since Delphi has no catering for building Delphi services or broadcast receivers, I’ve had to go “round the houses” to do it, using Java stubs, and pertinent thread-switching between the Java and Delphi threads.

As you will also perhaps appreciate, I don’t recommend this as a productive way of building an Android service. However if you need to add a service to a Delphi Android application, then this approach allows you to do so.

But… as of the time of posting there is a still the small matter of a (slightly brushed under the carpet) death-by-tombstoning bug on shutdown. If any keen reader can work out a clean way of closing I’d be most obliged to hear of it!

[Update]

When the small Java source files get compiled, the Android dx tool expects them to be compiled by the JDK 1.6.x compiler as opposed to the JDK 1.7.x compiler. If you have JDK 1.7.x installed, you hit a problem with dx reporting:

bad class file magic (cafebabe) or version (0033.0000)

However, to avoid forcing a reinstall of JDK 1.6 you might like to modify my build.bat batch files and add in extra command line switches to the javac.exe command-lines. You need to insert this after the javac.exe command to force Java 1.6 byte code output, which is digestible by the Android dx command:

-source 1.6 -target 1.6


Service example
===============
This project implements an Android service along with a couple
of broadcast receivers to catch and respond to intent messages
flung around the system. The service and receiver classes are
implemented as extremely shallow Java classes, which need to be
compiled and converted to an appropriate executable format
(dex), and then merged into the other dex code deployed with an
Android app.
The Java code calls into native Delphi code to implement
the "business end" of the service and receivers.
Build the Java support files:
----------------------------
In the project's java directory are some source files:
 - java\src\com\blong\test\ActivityReceiver.java
 - java\src\com\blong\test\SampleService.java
 - java\src\com\blong\test\ServiceReceiver.java
These need to be compiled to .class files, archived into a .jar
file, converted from Java byte code to DEX (Dalvik Executable)
format and merged into the normally used (by Delphi's Android
deployment process) classes.dex.
To set this up, follow these steps:
 - Ensure the useful subdirectory of Android SDK's build-tools
directory is on the system PATH (e.g. C:\Android\android-sdk-
windows\build-tools\18.0.1 or C:\Users\Public\Documents\RAD
Studio\12.0\PlatformSDKs\adt-bundle-windows-x86-20130522
\sdk\android-4.2.2)
 - Ensure the Java Development Kit's bin directory is on the
system PATH (e.g. C:\Program Files (x86)\Java\jdk1.6.0_23\bin)
 - Run a command prompt in the project's java subdirectory and
ensure you can successfully launch each of these:
    - javac
    - jar
    - dx
 - Review the build.bat file and ensure the environment
variables are set correctly:
    - ANDROID needs to point to your Android SDK base
directory, e.g. C:\Users\Public\Documents\RAD Studio\12.0
\PlatformSDKs\adt-bundle-windows-x86-20130522\sdk or
C:\Android\android-sdk-windows
    - ANDROID_PLATFORM needs to point at an installed SDK
platform installation, e.g. %ANDROID%\platforms\android-15 or %
ANDROID%\platforms\android-17. Check for one that is installed.
    - DX_LIB needs to point to the lib subdirectory under the
Android SDK build-tools directory, e.g. %ANDROID%\build-
tools\18.0.1\lib or %ANDROID%\build-tools\android-4.2.2\lib
    - EMBO_DEX needs to point to the Delphi-supplied Android
classes.dex file, wrapped in quotes to take care of any spaces
in the path, e.g. "C:\Program Files (x86)\Embarcadero\RAD
Studio\12.0\lib\android\debug\classes.dex"
 - Run build.bat
 - You should now have a new file in the project directory tree
called java\output\dex\classes.dex
This file replaces the supplied classes.dex and has the Java
service and broadcast receiver compiled classes included in it.
Set the new classes.dex for deployment:
--------------------------------------
Open the project in the IDE
Choose Project | Deployment
Note that the classes.dex file from the project's
java\output\dex directory is set to be deployed.
You must ensure that the default classes.dex file is de-
selected. As you switch configurations, this de-selection will
be lost (the file will be re-set to be deployed) and will need
to again be de-selected. This is an IDE bug with Delphi XE5 RTM
and XE5 UP1 and is logged in Quality Central as bug 118472.
Register the service:
--------------------
This has already been done for this demo. It involves the
following:
 - Open the Android manifest template,
AndroidManifest.template.xml, which is generated on first
compile, from the project directory
 - Add in a description of the service in the application
element:
 
<service android:name="com.blong.test.SampleService" />
Build the Delphi Android application library:
--------------------------------------------
In the IDE choose Project | Compile ServiceApp (or press
Ctrl+F9)
Deploy the library to an Android application package (.apk):
-----------------------------------------------------------
In the IDE choose Project | Deploy libServiceApp.so
Install the app on the device:
-----------------------------
In the IDE choose Run | Run Without Debugging (or press
Ctrl+Shift+F9).
This will implicitly do the compile and deploy steps above, so
they are actually optional.
This step will uninstall the app if already installed and then
install the newly built version.

第三部分:

Once upon a time I uploaded a Delphi sample app to the Google Play Store, written in Delphi XE5 and implementing an Android service. I wrote about the published app in this post and supplied the source in this follow-up post.

There was an issue that’s been hanging around with that sample project. When pulled into Delphi XE7 and updated so it all compiled nicely, it didn’t play ball when deployed. Instead it hung.

I’ve eventually worked through the to-do list enough to take a look at the problem. For one reason or another starting the service in the OnCreate event handler caused an issue thanks to some required thread synchronisation, which no longer functions as I wanted it to.

I’ve worked around the problem by very slightly delaying the service starting by use of a one-shot timer. Then the form setup is done and dusted by the time the service is invoked and all seems to be well.

An updated download archive is available here, which contains the original Delphi XE5 project and a Delphi XE7 equivalent, which should now be functionally equivalent.

分享到: