Post on 11-Feb-2022
transcript
Widgets, Native
Development and
Extras
1
Mobile Software Development
Dr. Péter Ekler PhD.peter.ekler@aut.bme.hu
Execute OS commands:
Process process =
Runtime.getRuntime().exec(“ls");
It’s a linux…
Some commands require root privilege
Some special tricks
Mobile Software Development2
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Process process = Runtime.getRuntime().exec("ls");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder logString = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
logString.append(line+"\n");
}
TextView tv = (TextView) findViewById(R.id.logTextView);
tv.setText(logString.toString());
} catch (IOException e) {
}
}
Some special tricks
Mobile Software Development3
Android AlarmManager
AlarmManager System Service
Enables to run operations even when none of
the activities is in the background
Executes an Intent
Enables repeated operation as well
Use carefully and always consider how/when to
stop the repeated operations
Requires typically a BroadcastReceiver that
receives the “Alarm” event
Mobile Software Development5
Schedule alarm// Create alarm intent.
Intent intent = new Intent(MainActivity.this,
WakeUpAlarmReceiver.class);
intent.putExtra("alarm_message", "mymessage");
PendingIntent sender =
PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
// Schedule alarm.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 10000, sender);
Mobile Software Development6
BroadcastReceiver for Alarmspublic class WakeUpAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
String message =
bundle.getString("alarm_message");
Toast.makeText(context, message,
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Manifest:
<receiverandroid:process=":remote“ android:name="WakeUpAlarmReceiver"/>
Mobile Software Development7
Cancel alarm
Intent intent =
new Intent(MainActivity.this,
WakeUpAlarmReceiver.class);
PendingIntent sender =
PendingIntent.getBroadcast(
MainActivity.this, 0, intent, 0);
AlarmManager am =
(AlarmManager)getSystemService(
A LARM_SERVICE);
am.cancel(sender);
Mobile Software Development8
Let’s practice
Create an AlarmClock application that
plays an mp3 when alarm is on!
Mobile Software Development9
Extending Android component model
Extend the application functionality:
Widget (mini application)
Live wallpaper
Useful and quick information for the user
New possibilities for development
Quick and easy to develop
Extend existing applications
Mobile Software Development11
Live wallpaper
Available from Android 2.1
Animated interactive wallpaper
Reaches the platform API (2D and 3D drawing,
GPS, sensors, network handling, etc.)
Example:
Animated wallpaper that changes the background
based on the current location or time
Google maps
Mobile Software Development12
Implementing life wallpapers
A Service that updates the wallpaper UI
onCreateEngine():
Creating WallpaperService.Engine object
The Engine is responsible for life cycle and drawing
It is very important to optimize the drawing because
of the CPU and Battery!
Handle life cycle functions carefully!
It is necessary to mark Live Wallpaper functionality in the
Manifest:
<uses-feature android:name="android.software.live_wallpaper" />
Mobile Software Development13
Event handling on live wallpaper
onVisibilityChanged():
When it is in the background we should pause the
drawing and possible threads.
onOffsetsChanged():
Canges between home screens
onTouchEvent():
Screen touch event
onCommand():
It is possible to send commands to the live wallpaper
Mobile Software Development14
Let’s practice
Create an application that
displays the current time on
the wallpaper when
touching the screen!
Mobile Software Development15
Live wallpaper - Manifest<manifest xmlns:android=http://schemas.android.com/apk/res/android
package="hu.bute.daai.amorg.examples">
<uses-sdk android:minSdkVersion="7" />
<uses-feature android:name="android.software.live_wallpaper" />
<application
android:label="@string/wallpapers"
android:icon="@drawable/ic_launcher_wallpaper">
<service
android:label="@string/my_wallpaper"
android:name=".MyWallpaper”
android:permission="android.permission.BIND_WALLPAPER">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data android:name="android.service.wallpaper“
android:resource="@xml/mywall" />
</service>
</application>
</manifest>
Mobile Software Development16
Live wallpaper – source 1/2
public class CubeWallpaper1 extends
WallpaperService {
private final Handler mHandler =
new Handler();
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public Engine onCreateEngine() {
return new CubeEngine();
}
class CubeEngine extends Engine {
private final Paint mPaint = new Paint();
private float mTouchX = 0;
private float mTouchY = 0;
CubeEngine() {
final Paint paint = mPaint;
paint.setColor(0xffffffff);
paint.setTextSize(25);
}
Mobile Software Development17
Live wallpaper – source 2/2
@Override
public void onCreate(SurfaceHolder surfaceHolder)
{
super.onCreate(surfaceHolder);
// Érintés eseményre kezelés jelzése
setTouchEventsEnabled(true);
}
@Override
public void onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
if (event.getAction()==
MotionEvent.ACTION_UP) {
mTouchX=-1; mTouchY=-1;
} else {
mTouchX = event.getX();
mTouchY = event.getY();
}
drawFrame();
}
void drawFrame() {
final SurfaceHolder holder =
getSurfaceHolder();
Canvas c = null;
try {
c = holder.lockCanvas();
if (c != null) {
c.save();
c.drawColor(0xff000000);
c.drawText(
new Date(System.currentTimeMillis()).
toLocaleString(),
mTouchX, mTouchY, mPaint);
c.restore();
}
} finally {
if (c != null)
holder.unlockCanvasAndPost(c);
}
}}} // osztály bezárása
Mobile Software Development18
Widgets – mini applications
Small applications that are typically
embedded in the home screen
Can contain UI controls
Refresh state periodically
E.g.: music player
Mobile Software Development20
Widget components AppWidgetProviderInfo:
XML based
Meta data (layout, refresh interval, AppWidgetProvider class)
AppWidgetProvider:
Programming interface
Broadcast events: updated, enabled, disabled, deleted
View layout:
XML
Configuration Activity:
Optional
Launches at widget first start
Mobile Software Development21
Widget Manifest<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hu.bute.daai.amorg.examples"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<!-- Broadcast Receiver fog frissíeni -->
<receiver android:name=".HelloWidget" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider„
android:resource="@xml/hello_widget_provider" />
</receiver>
</application>
</manifest>
Mobile Software Development22
Widget AppWidgetProviderInfo XML
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android=
"http://schemas.android.com/apk/res/android"
android:minWidth="146dip"
android:minHeight="72dip"
android:updatePeriodMillis="500"
android:initialLayout="@layout/main"
/>
Mobile Software Development23
Widget Layout<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:background="@drawable/amorg"
android:layout_gravity="center"
android:layout_height="wrap_content">
<TextView android:id="@+id/widget_textview"
android:text="@string/hello_text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal|center"
android:layout_marginTop="5dip"
android:padding="10dip"
android:textColor="@android:color/black"/>
</LinearLayout>
Mobile Software Development24
Widget AppWidgetProviderpublic class HelloWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context,
AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// refresh
}
}
Mobile Software Development25
Which statement is false?
A. Widget is basically a BroadcastReceiver
component.
B. Live Wallpaper is basically a Service
component.
C. Widgets can not contain UI controls like
buttons.
D. Live wallpaper can handle touch events.
Mobile Software Development26
Mini application on the home screen
Two refresh state:
Periodic refresh (minimum 30 mins)
Refresh via AlarmManager
Part of HomeScreen process
Initialized by a BroadcastReceiver
Continous refresh:
Launch a Service at onUpdate() that contains a
thread
Widget summary
Mobile Software Development27
Let’s practice!
Create a widget that
refreshes its content in every
5 seconds!
Mobile Software Development28
Android NDK
NDK: Native Development Kit
NDK enables to create and reach native class libraries
from Java code
How can we do that?
JNI: Java Native Interface
Well known C++ development
Advantages:
Increase in speed
Code reuse (C++)
Download NDK:
http://developer.android.com/tools/sdk/ndk/index.html
Mobile Software Development31
What does NDK offer?
Different tools and libraries for C and C++
compiling
Embed native class libraries into standard
Andorid applications (apk)
Natív class headers and libraries (e.g. native
Activity)
Documentation, examples and numerous
tutorials
Mobile Software Development32
NDK hardware support
ARMv5TE (Thumb-1 instructions as well)
Supports ARM based devices
ARMv7-A (Thumb-2 and VFPv3-D16 instruction,
with optional NEON/VFPv3-D32 support)
Hardware FPU
x86 instructions
Note: Target can be defined in the
Application.mk file
Mobile Software Development33
When does it worth to use NDK? 1/2
In many cases it is not required!
Think about the advantages and
disadvantages!
NDK does not increase speed always, but
it always increase complexity
Use only when it is really needed!
Mobile Software Development34
When does it worth to use NDK? 2/2
Worth to use when:
Independent task
CPU intense operation where memory handling is
important
Signal processing
Physics simulation
Graphics (e.g.: 3D)
It is always worth to check whether there is an
existing Android API for it
Re-use working C/C++ libraries
Mobile Software Development35
How to use native code?
Reach native library via JNI:
We can use standard Android tools
Call native library via JNI
Works on Android 1.5 and above
Native Activity:
Android 2.3 and above
NativActivity C++ class with life cycle methods
Other components are not implemented in
native code
Mobile Software Development36
Supported native libraries 1/2
libc (C library) headers
libm (math library) headers
JNI interface headers
libz (Zlib compression) headers
liblog (Android logging) headers
Mobile Software Development37
Supported native libraries 2/2
OpenGL ES 1.1 and OpenGL ES 2.0 (3D
graphics library) headers
libjnigraphics (reach pixel buffers) header
(Android 2.2 and above).
C++ supporting headers (minimal set)
OpenSL ES native audio library
Android native application library
Mobile Software Development38
NDK documentation 1/3
INSTALL.HTML: NDK install and configuration
OVERVIEW.HTML: NDK abilities
ANDROID-MK.HTML: The structure of the Android.mk file
APPLICATION-MK.HTML: Application.mk file structure
CPLUSPLUS-SUPPORT.HTML: C++ support description
CPU-ARCH-ABIS.HTML: CPU architectures and keys
CPU-FEATURES.HTML: Introduces the cpufeatures static
library that can be use to detect CPU type and capabilities
during runtime
Mobile Software Development39
NDK documentation 2/3
CPU-ARM-NEON.HTML: compilation steps to ARM
NEON and VFPv3-D32
CHANGES.HTML: changes in the current release
DEVELOPMENT.HTML: NDK release package
preparation steps
HOWTO.HTML: General information about NDK usage
IMPORT-MODULE.HTML: share and re-use modules
LICENSES.HTML: connected open source licenses
NATIVE-ACTIVITY.HTML: native Activity introduction
Mobile Software Development40
NDK dokumentáció 3/3
NDK-BUILD.HTML: Introducing the ndk-build script
NDK-GDB.HTML: Native code debugger description
PREBUILTS.HTML: static and dynamic shared libraries
STANDALONE-TOOLCHAIN.HTML: how to use the
standalone compiler
SYSTEM-ISSUES.HTML: known bugs and issues
STABLE-APIS.HTML: APIs (headers) introduction
OVERVIEW.HTML: Overview
Mobile Software Development41
NDK development environment
NDK download:
http://developer.android.com/tools/sdk/n
dk/index.html
Install Eclipse NDK plugin
NDK configuration: set NDK folder in
Eclipse
Right click on the project: “Add native
support”Mobile Software Development42
NDK project elements 1/4
Android project folder can not contain
spaces!
New library: jni
All native components goes in the jni
folder:
Android.mk
Application.mk
hello.c
Mobile Software Development43
NDK project elements 2/4
Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# modul name and sources
LOCAL_MODULE := hello
LOCAL_SRC_FILES := hello.c
include $(BUILD_SHARED_LIBRARY)
Mobile Software Development44
NDK project elements 3/4
Application.mk:
APP_PLATFORM := android-8
APP_ABI := armeabi-v7a
Mobile Software Development45
NDK project elements 4/4
hello.c:
#include <string.h>
#include <jni.h>
jstring
Java_hu_bute_daai_amorg_examples_NativeLib_sayHello(JNIEnv* env,
jobject javaThis) {
return (*env)->NewStringUTF(
env, "Hello Android Csoport - nativ!");
}
jint Java_hu_bute_daai_amorg_examples_NativeLib_add(JNIEnv * env,
jobject javaThis, jint value1, jint value2) {
return (value1 + value2);
}
Mobile Software Development46
First NDK application
NativeLib.java class:
public class NativeLib {
static {
System.loadLibrary("hello");
}
// native functions with same name as in hello.c
public native String sayHello();
public native int add( int v1, int v2 );
}
Mobile Software Development48
First NDK application
Usage from an Activity:
public class NativeTestActivity extends Activity {
private NativeLib nativeLib;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nativeLib = new NativeLib();
// Natív kód hívása
String hello = nativeLib.sayHello();
new AlertDialog.Builder(this).setMessage(hello).show();
}
}
Mobile Software Development49
NDK example
Calculate PI value through 1000000
iteration
Define CPU capabilities in Application.mk
file:
APP_PLATFORM := android-8
APP_ABI := armeabi-v7a
Mobile Software Development51
Let’s practice!
Create an Android application
that calls native functions:
sayHello()
add(int a, int b)
pi(int iteration)
Calculate PI value via a specific
number of iterations
Mobile Software Development52
Let’s practice!
Create an Android application
that reads out the light sensor
values from native code!
Create a button that can be
used to enable and disable
light sensor reading!
Mobile Software Development53
Simple XML: XML serialization
http://simple.sourceforge.net/
ORM Lite: Object Relation Mapping
http://ormlite.com/sqlite_java_android_orm.shtml
Android UI patterns / Android patterns
https://play.google.com/store/apps/details?id=com.groidify.uipatterns&h
l=hu
http://www.androidpatterns.com/
kSoap: SOAP Web Service support
http://code.google.com/p/ksoap2-android/
box2D: 2D physics engine
http://code.google.com/p/androidbox2d/
AndEngine (contains box2D): Game engine
http://www.andengine.org/
Libraries 1/3
Mobile Software Development55
libGDX: drawing and contains box2D as well
http://code.google.com/p/libgdx/
Acra / Bugsense: crash log
http://acra.ch/
https://github.com/ACRA/acra
Java Mail
http://code.google.com/p/javamail-android/
OpenCV: computer vision
http://opencv.org/platforms/android.html
Libraries 2/3
Mobile Software Development56
ActionBarSherlock: ActionBar for Android 2.X,
already contains the SupportLib!
http://actionbarsherlock.com/
Unity: game engine
http://unity3d.com/unity/multiplatform/mobile
Commons.net: Apache Common Modul
http://commons.apache.org/net/
Zxing: barcode and QR code scanning
http://code.google.com/p/zxing/
Libraries 3/3
Mobile Software Development57
Display advertisement
~5000 advertisement display ~ 3$
http://www.google.com/ads/admob/
Library:
https://developers.google.com/mobile-ads-sdk/
Developer gets an AdMob publisherID that
should be defined in the XML as the unit ID
For testing, the id should be checked in the
LogCat
AdMob
Mobile Software Development58
<com.google.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="MY_AD_UNIT_ID"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR,
TEST_DEVICE_ID" />
AdMob layout
Mobile Software Development59
http://coderesearchlabs.com/androidpdfwri
ter/
Supported functions
Page size
Font type
Embedding images
Drawing shapes
Android PDF Writer
Mobile Software Development60
Let’s practice
Create an application that
generates a PDF!
Library:
http://avalon.aut.bme.hu/~tyrae
l/androidtanfolyam/pdfwriter.jar
Mobile Software Development61
Cross-platform game development
framework
CPU intensive parts on Native libs
Useful pages:
http://libgdx.badlogicgames.com/
http://code.google.com/p/libgdx-users/
http://obviam.net/index.php/getting-started-in-
android-game-development-with-libgdx-
create-a-working-prototype-in-a-day-tutorial-
part-1/
LibGDX
Mobile Software Development62
Let’s practice!
Create an application with
LibGDX that displays a ball!
Mobile Software Development64
Acra Crashlog
Crash report to Google Docs, BugSense,
E-mail or personal page
Easy to use
Automatic crash report
More details
http://code.google.com/p/acra/wiki/ACRAHow
To
Mobile Software Development65
Andriod 4.X versions
4.0 (14), 4.0.3 (15): Ice Cream Sandwich
4.1, 4.2, 4.3 (16, 17, 18): Jelly Bean
4.4 (19): KitKat
Detailed API changes:
http://developer.android.com/sdk/api_diff/18/changes.
html
General description:
http://developer.android.com/about/versions/jelly-
bean.html
App! Android update68
4.0 and 4.0.3 new features
New Social API and Contacts Provider
Invite Intent
VoiceMail provider
Camera.FaceDetectionListener
Camera broadcast intent-ek
Camera.ACTION_NEW_PICTURE, Camera.ACTION_NEW_VIDEO
Spell Checker Service
Hover events (stylus and mouse is also supported!)
Text To Speech features
READ_SOCIAL_STREAM and WRITE_SOCIAL_STREAM
permissions
69 App! Android update
4.1 new features
App stack navigation
android:parentActivityName="hu.bme.aut.amorg.callhierarchydemo.app.MainActi
vity„
getParentActivityIntent(): Intent, that can start the logical parent of the Activity
New Media Codec
Andriod Beam
Bluetooth support for large data
Wi-Fi P2P service discovery
RenderScript
Copy paste with Intents
TV support<uses-feature android:name="android.hardware.type.television"
android:required="true" />
70 App! Android update
4.2 new features
DayDream
When connected to docking station or charger
Passive and active
Secondary screens
LockScreen widget
Multiple user support
Embedded fragments
Renderscript new features
Blend, Blur, Colro matrix, stb.
71 App! Android update
4.3 new features
Bluetooth Low Energy
<uses-feature android:name="android.hardware.bluetooth_le"
android:required="true" />
Media DRM advanced features
OpenGL ES 3.0
<uses-feature android:glEsVersion="0x00030000" />
ViewOverlay support
Window attach and focus events without direct View reference
ViewTreeObserver.OnWindowAttachListener
ViewTreeObserver.OnWindowFocusChangeListener
NotificationListenerService
Automated UI testing
72 App! Android update
Android 4.4
"It's our goal with Android KitKat to
make an amazing Android experience
available for everybody„
App! Android update73
Android 4.4 Features
On-device profiling
Print support
IR support
SMS provider (advanced)
Total full screen
Chromium WebView
Renderscript features
RTL localization support (advanced)
74 App! Android update
The Objectives of an Android Architect
Choose proper Android version
Design application architecture (components)
Check UI design (mockup vs. specification), tablet support
Design network communication (protocol, security, etc.)
Clarify performance issues (e.g.: do we need native support?)
Check special functions and algorithm requirements
Choose proper external libraries
Design test environment
Code quality, best practices
Java, Java, Java, … (efficiently!)
Joshua Block: Effective Java
Mobile Software Development76
Further Objectives of an Architect
Continuous Integration design and
monitoring
Use version control system properly (GIT,
SVN, etc.)
Library dependency check
Clarify license conditions
Clarify the publication mechanism of the
application
To sum up: always find the best solution!Mobile Software Development77