0% found this document useful (0 votes)
1K views

Mobile Devices Programming 2019

- The document outlines the structure and requirements for a course on mobile device programming using Android. - The course consists of 15 lectures and 10 laboratories over the semester. Student progress and results will be evaluated based on completed laboratory tasks, challenges from lectures, a final test exam, oral exam, and optional project. - Topics covered in the course include Java basics, XML basics, the Android architecture, application development stages, and programming using common Android APIs like menus, databases, maps, hardware sensors and graphics.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Mobile Devices Programming 2019

- The document outlines the structure and requirements for a course on mobile device programming using Android. - The course consists of 15 lectures and 10 laboratories over the semester. Student progress and results will be evaluated based on completed laboratory tasks, challenges from lectures, a final test exam, oral exam, and optional project. - Topics covered in the course include Java basics, XML basics, the Android architecture, application development stages, and programming using common Android APIs like menus, databases, maps, hardware sensors and graphics.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 159

android

mobile devices programming


dr inż. Piotr Bednarczuk
[email protected]
course information
sylabus – course plan and scope the structure of each lecture
four parts:
time table: theory: definitions, descriptions
15 lectures, 90 min example: short examples
10 laboratories, 90 min exercise: exercises to do together on lecture
lab: tasks to do by yourself on laboratory

consultations:
on every Wednesday at 4:45 pm
how to complette the course
final result will be based on:

laboratory lecture
lab task or project challenges
(more then 50% completed) (2 of 3 completed )

final test exam final oral exam


(on the last two laboratories) (on the last two lectures)

final result = (oral exam result + lab test result) / 2


lab tasks realisation - rules
additional the possibility to pass the laboratory
insted of pass final test exam
but only for students who takes part in laboratory
participation – not mandatory, only possilbility do grade laboratory
more then 50% completed tasks means passed final test exam:
but only tasks completed on laboratory
except tasks completed as a homework
project - rules
additional the possibility to pass the laboratory
presentation and passing the project:
the subject of the project should be consulted with and the project should be presented by yourself
accepted by the teacher during the presentation, you may be asked
questions about how to perform a given functionality
project exempts from final lab test exam
degree adequate to the number of different modules used: --> the project should include modules in way
3 for 3 modules, 4 for 4 modules, 5 for 5 modules
practiced at the lecture and laboratory,
the project should be created at the laboratory only these modules will be graded :
and also completed as a homework
menu
please also take care of the look of your mobile application database
project structure: maps
hardware ( SMS or phone )
the project should have a subject sensors
using every module should have justification and have graphics, ( canvas )
match to subject multimedia ( audio, video)
project should be made by yourself and contain developer widgets ( application type, not controls )
info

deadline: the last laboratory, Jan 2020


challenges - rules
additional the possibility to pass the lecture
insted of pass oral exam
but only for students who takes part in lecture
participation – not mandatory, only possilbility do grade lecture
2 of 3 completed challenge means passed oral exam

sit far away from another student


must not use smartfones, laptops and any electronics devices
must not talking to another students
you can use only your note
android inspiration - rules
the only possibility to increase your final result
short presentation about some interesting android project or application
which you would like to present and recommend your colleagues
the selected android application must be approved by the Teacher

presentation :
max 15 minuts on lecture or laboratory
max 5 slides
reasons for choosing a android application
functionality
popularity
your inspirations base on this application
android inspiration - exapmle

external presentation …
final exam, test and project terms
laboratory – final tests
the last laboratory, Nowember, 2019
project presentation deadline:
the last laboratory, November, 2019
lecture – final oral exam
the next to last lecture, January, 2020
final oral exam rules
3 questions

result:
1 correct answer - 3
2 correct answers -4
3correct answers -5
results and makeup exams terms
laboratory
during the exam session, January/February,2020

lecture
the last lecture, January, 2020
textbook - en
Satya Komatineni, Dave MacLean, Sayed Hashimi: Pro Android 3 –
Android 3 platform SDK techniques for developing smartphone and table apps,
Apress, 2011
--------------------------------------------------------------------------------------------------------------------
Ian F. Darwin, Android Cookbook:
Problems and Solutions for Android Developers
O’REILLY, 2017

the best thing to do is to attend the lectures:


• make notes, and read the lecture notes
• consult and complete knowledge from the textbooks
textbook - pl
recomended polish book:

Satya Komatineni, Dave MacLean, Sayed Hashimi:


Pro Android 3 – tworzenie aplikacji, Helion 2012
--------------------------------------------

Ian F. Darwin - Android. Receptury – O’REILLY – 2013

----------------------------------------------
Dawn Griffiths, David Griffiths, Android. Programowanie aplikacji. Helion 2015
useful tools - web sites

http://developer.android.com
excellent training platform for android developers

http://startandroid.ru – sample android projects


lecture scope
• Java basics
• XML basics
• what is android (java + xml)
• architecture
• stages of application development
• programming in the Android environment:
menu, database, google maps, hardware ( SMS or phone ), sensors, graphics, ( canvas ),
multimedia ( audio, video), widgets ( application type, not controls )
• implementation of the application on the market
• mobile application generators
what is android ?
operating system designed specially for mobile devices
based on Linux Kernel
was created at small firm Android
the company was bought by Google in 2005, leaving the Android as the system name
currently Android standard is created by the Open Handset Alliance cluster
the cluster consists of and developed by 78 companies such as:
Google, HTC, Dell, Intel, Motorola, Samsung, LG Group, T-Mobile
android
architecture
Application layaut ( our application)
framework, application server
libraries, functionality engines
runtime environment
DVM - Dalvik Virtual Machine
now ART - Android Runtime (4.4)
Linux kernel with drivers
Android = Java + XML

let's remember the fundamentals of Java and XML programming


Java - syntax
A class is a collection of fields (data) and methods (procedure or function) that
operate on that data.

class className [extends superClassName]


{
[fields declaration]
[methods declaration]
}
Java – syntax - field
field can be:
static variables access levels
variables
Java – syntax - method
methods are declared inside the body of the class but immediately after the
declaration of data fields.
the general form of a method declaration is:

type methodName (parameter-list)


{
method-body;
}

methods are embedded in classes


Java - method declaration - header
A method declaration begins with a method header
class MyClass
{ …
public int MyMethod ( int n1, char c2 )

method
name parameter, atributes list

parameter list specifies the type


return and name of each parameter
type
name of a parameter in the method
properties declaration is called a formal argument
Java - method definitione - body
The header is followed by the method body:

class MyClass
{

private int MyMethod(int num1, int num2)
{
int minValue = num1 < num2 ? num1 : num2;
return minValue;
}


}
Java - create and use an Object
in Java, an object is created from a class
when we had already created the class named MyClass,
so now we can use this to create objects.
to create an object of MyClass, specify the class name, followed by the object name, and use
the keyword new:
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();

}
}
Java - the return statement
a method returns to the code that invoked it when it:
completes all the statements in the method,
reaches a return statement, or
throws an exception (covered later),

the return type of a method indicates the type of value that the method sends back to the
calling location

a method that does not return a value has a void return type

the return statement specifies the value that will be returned

returning a class or Interface


Java in Android
In Android Java is used to code functionality
XML
XML stands for eXtensible Markup Language
XML is a markup language much like HTML
XML Does Not Use Predefined Tags
XML is a self-descriptive
XML was designed to store and transport data
XML is a W3C Recommendation
XML syntax
XML documents must have a root element:

<root>
<child attributeName= "attributeValue">
<subchild>.....</subchild>
</child>
<!-- This is a comment -->
</root>

NOTE: all XML elements must have a closing tag


XML elements must be properly nested
XML attribute values must always be quoted eg. ”a”
XML element
An element can contain:
text
attributes
other elements
or a mix of the above
XML element naming rules:
element names are case-sensitive
element names must start with a letter or underscore
element names cannot start with the letters xml (or XML, or Xml, etc)
element names can contain letters, digits, hyphens, underscores, and periods
element names cannot contain spaces
XML in Android
in Android XML is used to configure application and window’s layouts
in Android, the main descriptor of the application is also saved in XML: Manifest.xml
Java vs Android – the main differences
Functionalities Java Android
Application life cycle static public method: static main metody onCreate, onResume,
onPause, onDestroy
Virtual machine JVM Dalvik, ART - Android Runtime (4.4)
Design pattern MVC (Model-View-Controller) Layouts in many XML, Activity or
fragments
Libraries Java used AWT (Abstract Window View Objects.
Toolkit) and Swing library
IDE Eclipse Android Studio

syntax the same the same


stages of application development
stage 1. configuration of the developer environment - Android Studio
stage 2. creating and configuring the device emulator
stage 3. application codding
stage 4. launching the application
launching the application on the device emulator
launching the application directly on the device
stage 5. testing the application on many devices
stage 6. implementation of the application on the market
publication in the Android Market - Google Play
publication on alternative place: webshop, website
IDE - Integrated Development Environment
JDK + SDK
1. JDK instalation (Java Development Kit) – if not exists
http://www.oracle.com/technetwork/java/javase/downloads
2. Android Studio instalation - SDK (Android Software Development Kit)

https://developer.android.com/sdk
IDE - configuration
JAVA – optional - only if needed
if we get a error message about the lack of path to JDK we need to add it to the
environment variables JAVA_PATH for jdk java:
EN
Start menu > Computer > System Properties > Advanced System Properties. Then
open Advanced tab > Environment Variables and add a new system variable
JAVA_HOME that points to your JDK folder, for example C:\Program
Files\Java\jdk1.7.0_21.
PL
Start\Ten Komputer\Właściwości\Zaawansowane ustawienia systemu\Zmienne
środowiskowe\ po średniku, dodać ścieżkę do katalogu z \JAVA\SDK\bin\ np.:
;d:\JAVA\SDK\bin\
android – your first application
1. create a new Android Studio project

2. configure the project


set the application name and company domain, and a location for project
files is created.

NOTE – IMPORTANT !
PackageName – the package name serves as the application identifier and
must be unique. This identifier will also be used to identify the application
in GooglePlay. So you can't use names that someone has previously used or
reserved, e.g.. com.google, com.android, com.example.
CreateActivity - in the project creation window, you must also select the
CreateActivity activity and enter its name. By default, Android will launch
this activity first when you start the application, but you can change it in the
launch configuration.
first app - min SDK version
The next window for the application appears, we choose Phone and Tablet and the minimum SDK version of
Android

NOTE – VERY IMPORTANT !

The minimum SDK version should be equal to or


lower than Android version on your mobile device
first app– window type – activity type
first app – first activity
in the activity wizard of the first activity \ window we specify:
the name of the first \ main activity
layout names - XML with structure
header, window label
main menu names - XML from the menu

... and this completes the creation


of the window in the wizard,
it's still development
IDE – Android Studio
The most useful IDE elements:
project structure: View->Tool Window - > Project
create a new project: File->New->New Project
build project : Build->Make Project
run application: Run->Run
configuration of running / debugging the application : Run->Edit Configuration
package installation : Tools->Android->SDK Manager
emulator configuration and running : Tools->Android->AVD Manager
result of building and running : View->Tool Window->Messages\Gradle Console
IDE configuration - SDK Manager
SDK packages instalation
additional packages can be installed from the
SDK Manager package manager, in the menu select:
Tools\Android\SDK Manager

SDK packages localisation


where the SDK package files are saved
is specified in:
Project Structure \ SDK Location
emulator configuration

The list of available emulators is in:


Tools-> Android -> AVD Manager
We can also create our own
emulator using the :
Create Virtual Device
emulator configuration
when creating your own
emulator you should
specify:
device category
model
screen size
resolution
memory size
screen orientation
camera
Emulator: ERROR: x86 emulation currently
requires hardware acceleration
to solve this problem:
1. instal the Intel x86 Emulator Accelerator package
2. run the intelhaxm-android.exe application from the location
…\sdk\extras\intel\

SDK directory
localisation→

3. Restart Android Studio and launch AVD Manager.


run application on emulator
First of all we launch the emulator in the Android Virtual Device
Manager window. We run the emulator only once by selecting the
configured emulator from the list and pressing the button in the
Action column. Then to start the application is enough:
Run-> Run.
run application on emulator - configuration
you can also set the parameters for running the
application on the emulator, select Run-> Edit
Configuration in the configuration set / select:
apps
emulator
launched window
Uwagi:
If we do not have the emulator running yet, it may take some
time for the emulator to start, because a virtual Android
device must be created in the background in the background.
It can take up to several minutes. Once we have launched the
emulator earlier, the android application should appear on
the emulator relatively quickly.
When running the application on the emulator, you may need
to install additional packages using the SDK Manager available
from the Tools-> Android -> SDK Manager menu.
run application on emulator - error
Sometimes, with incorrectly defined
emulator parameters, an error may
appear:
This means that we need to install the
"Intel x86 Emulator Accelerator (HAXM)"
hardware acceleration package. For intel
processors from the Extras section. We run
Tools-> Android-> SDK Manager, select the
necessary package in the Extras section
and install it, accepting the license along
the way.
run application on android device – way 1
upload apk file to android device
To upload the application on the phone you need only 6 steps:
1. The apk application can be found in the directory: Project name \ app \ build \ outputs \ *. apk
2. We connect the phone to the computer using a USB cable in the multimedia device mode so
that the computer can see the resources (files, catalogs) of the device.
3. We change the device settings so that you can install applications from sources other than
Google Play. Settings-> Security and select Unknown sources
4. We use the available Android file manager: Applications -> My Files -> All files or we use another
file manager, e.g. DropBox
5. We are losing the * .apk file from the computer to any directory on the device, using e.g.
Windows. You can also create a separate catalog for your own programs.
6. We are looking for our application on the phone, we install and run it.
run application on android device – way 2
run apk file in android device directly
To run the application on the phone you need only 3 steps:
1. check on mobile device setting in Programmers options check box Debugging USB
2. set BuildType to debud in File\Projekct Structure\BuildType for app
3. run the application on chosen mobile device

NOTE - this path may not be available


due to an incorrect USB cable
android- debug
android base on Linux kernel
DDMS
Dalvik Debug Monitoring Service
breakpoints
Android SDK Debug tools
ADB (Android Debug Bridge)
LogCat
HierarchyViewer
android – debug - LogCat
LogCat contains:
Logging application execution on the emulator device
Real-time login, application launch
Works with priority tags, filters
android program structure
AndroidManifest.xml – the main application descriptor
src - source code directory, with Java code
res – folder with application resources
drawable – directory with image files and image descriptors
anim – directory with animation files and xml descriptors
layout – definitions of application views in xml files,
we will see here what our application windows will looks like
menu – munu xml descriptor files
values – other application resources, e.g. thongs, tables, styles
and colors
xml – other xml files describing the application
raw – additional application data
manifest – the main application descriptor
name : … AndroidManifest.xml
semilar like web.xml w Javie2 - J2EE.
The manifest defines the content and behavior of the application,
list of activities, service providers and permissions to run them.
You will also find information on exchanges regarding the device :

<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="7" />
manifest – the main application descriptor
The manifest also includes settings for the <activity
android:name=".MainActivity"
application, e.g.
android:label="@string/app_name" >
list of used windows <intent-filter>
main application window <action
android:name="android.intent.action.MAIN" />
used system components, e.g. SMS
<category
identifiers for Google Play android:name="android.intent.category.LAUNCHER" />
</intent-filter>
in the example on the left we can see two
</activity>
windows, two activity markers -->
<activity
android:name=".ListActivity"
android:label="@string/title_activity_list" >
</activity>
android – controls 1
Layout - group of controls for arrangement of elements on the window :
Widgets – basic user interface controls (buttons, bars, fields)
android – controls 2
Date & Time – date and time controls
Text Fields – text fields
Expert – specialized controls
Containers – containers, lists, views
android - notyfication
There are several ways to notify and display messages:
Toast Toast.makeText(this, “Notification text”, Toast.LENGTH_SHORT).show();

AlertDialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

builder.setMessage(R.string….
Notification .setPositiveButton(...
.setNegativeButton(...
android – button handling
We add a button, we give it a button1 identifier.
In MainActivity.java we add a method, e.g. ShowMessageButton.
Now in the newly created method we create a reference to our object.
Button btn1 = (Button) findViewById (R.id.button1);
Note: in the case of a declaration of a class object for which we do not have an
imported package to import the missing package
just select the object and use Alt + Enter ----->
The most important when handling events is to listen - Listener, so you also need to
create an Listener (listener) of events, e.g. clicking on the button.

btn1.setOnClickListener(new View.OnClickListener()
android – button - example
the whole method will look like this:

private void ShowMessageButton() {


//adding a reference to our button
Button btn1 = (Button) findViewById(R.id.button1);
// adding event listener
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(
MainActivity.this,
" You have just pressed the button ",
Toast.LENGTH_LONG
).show();
}
});
}
android – button - example
The only thing left in the main onCreate method of the MainActivity class is we add a call to the button
handling method:

public class MainActivity extends ActionBarActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ShowMessageButton();
}
android - menu
there are two type menus on Android:
- the main application menu, available under the menu button
- context menu, accessible after pressing an application element, e.g. window, fields.
the main methods:
onCreateOptionsMenu
onOptionsItemSelected

menu can be created:


- in the XML menu file
- programmatically - AddRegularMenuItem
android- menu - xml
We add a new menu.xml file by clicking on the branch ... menu-> New-> Menu resource file, this will create a file for us
…app\src\main\res\menu\*menu*.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="@+id/menuGroup_Main">
<item android:id="@+id/menu_start"
android:orderInCategory="10"
android:title="Start" />
<item android:id="@+id/menu_message" NOTE:
android:orderInCategory="20" It is worth numbering the menu not every one so that you
android:title= " message from menu" /> can sometime add items between the originally created
<item android:id="@+id/menu_exit"
order without renumbering the entire menu.
android:orderInCategory="30"
android: orderInCategory = "10"
android:title="Wyjście" />
</group>
</menu>
android - menu - java
We define support for menu buttons in the file ... \app\src\main\java\ ...
\MyActivityMenu.java
First, in the OnCreateOptionMenu method you need to load, associate with the program
the menu from the menu.xml file that we just created.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu); // linking the menu with an xml file
return true;
}

NOTE: For the menu to be shown, the onCreateOptionsMenu method must return True.
R.menu.menu
R.string.value
android – menu – menu items added
programmatically
1. We add a menu variable in the main project class.
public class MainActivity extends ActionBarActivity {
Menu appMenu = null;
2. In the onCreateOptionsMenu method, we add a method for creating a program menu
this.appMenu = menu;
AddRegularMenuItem(menu);

3. And in the AddRegularMenuItem method we add an item to the menu
private void AddRegularMenuItem(Menu menu) {
int base=Menu.FIRST;
menu.add(base,base,base," new program-added item ");
menu.add(base,100,100," new program-added item at the end of the list ");
}
Android – menu – event handling
In the onOptionsItemSelected method, we support click events on given
menu buttons.
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_start) {
return true;
}else if (id == R.id.menu_message) {
TextView tv = new TextView(this); tv.setText("Message from Android App"); setContentView(tv);
}else if (id == R.id.menu_exit) {
finish();
}else if (id == 100) {
Toast.makeText(MainActivity.this, " You pressed the program-added menu item ",
Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
android – context menu
the context menu is launched in the context of an contrlos (button, view, text field, etc.)
NOTE: is necessary by holding your finger on a given element for longer.
the context menu does not support submenus.

the mail methods:


registerForContextMenu – add context menu to the control
onContextItemSelected – selected menu item event hanling
android–context menu–context object
We add a TextView control, in it we will call the context menu.
set id of the TextView control to txtView1

inside OnCreate method add code:


TextView tv = (TextView)this.findViewById(R.id.textView1);
tv.setText("contex menu");
registerForContextMenu(tv);

Of this, the most important is the registerForContextMenu method which adds a


context menu to the object.
android – context menu - items
Then we define the content of the context menu in the onCreateContextMenu method:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.setHeaderTitle("context menu");
menu.add(200, 200, 200, "element 1");
menu.add(300, 300, 300, "element 2");
}
android – context menu – events
We also create a method to handle the menu in the onContextItemSelected method:
@Override
public boolean onContextItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == 200) {
return true;
}else if (id == 300) {
return true;
}
return super.onContextItemSelected(item);
}
android – activity- window
android – activity – the main window
the window that appears first is specified in the
manifest in the application section
android – activity – layout
<?xml version=“1.0” encoding=“utf-8”?>
<LinearLayout
xmlns:android=“http://schemas.android.com/apk/res/android”
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>

<TextView
android:id=“@+id/componentName” Table Layout
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text=“Text that will be displayed.”
/>
</LinearLayout>
android – activity lifecycle
• Open
• Create
• Start\Restart
• Resume
• Running
• Pouse
• Stop\Kill
• Destroy
• Shut Down
android – intent
intent is Intention to do something
the intention is an abstract description of the actions or actions to be carried out
the intention allows you to decide for which component (Activity, Service, Recipient of
content) trigger what action or share what data.
Intentions enable communication between controls
- send messages and packets - bundle
- receiving messages
Example:
the intention to launch another window from the level of the window in which we are
currently located:

Intent intent = new Intent(CurrentActivity.this, OtherActivity.class);


startActivity(intent);
android – intent – example
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button listener
Button btnStart = (Button) findViewById(R.id.btn_start);
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent =
new Intent(CurrentActivity.this, OtherActivity.class);
startActivity(intent);
}
});
}
android – additional activities
when creating a new window we specify:
window type, e.g. with fragment or map support
window name
whether the window should be launched
directly from the phone as a new tile, icon
whether the window should have a parent

Important methods:
Intent intent = new Intent(this, GaleryActivity.class);
startActivity(intent)
android – additional activities - fragments
we add new windows in the application
through the context menu on the app
project -> New -> Android Activity and
select TabbedActivity, let's call it
Main2Activity.
let's choose the Swipe View (ViewPager)
Navigation Style, i.e. the window with a
finger gesture with the fragment name
as the parent class - HerarchicalParent let's
not set anything, we will change later.
android – additional activities - fragments
In the Main2Activity.java file, let's change that our class inherits from Activity and not
ActionBarActivity.

public class GaleryActivity extends Activity implements

Now let's call this window from the context menu, we change the name of the context
menu element:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.add(200, 200, 200, "fragment window");
}
android – additional activities - fragments
transferring data between activities
we also transfer data to the second window using the intent.
in the window from which we want to transfer data, we use the puntExtra method,
after creating the intention and before calling the window to which we transfer data:

Intent intent = new Intent(this, Main2Activity.class);


intent.putExtra("text", " Text which is to be passed to the second ativity ");
startActivity(intent);
android – additional activities - fragments
in the window in which we want to receive the data we use the Bundle object and the
method GetExtras():

Intent i = getIntent();
Bundle b = i.getExtras();
String pt = b.getString("tekst");

the transmitted text can be displayed in the text field:

txv = (TextView) findViewById(R.id.txv2);


txv.setText(pt);
android – additional activities - fragments
in the onContextItemSelected method, we add a call to our window using the intention:

@Override
public boolean onContextItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == 200) {

Intent intent = new Intent(this, Main2Activity.class);


startActivity(intent);

}else if (id == 300) {


android - hardware
telephone i SMS
photo camera
WIFI
run application on android device – way 1
upload apk file to android device
To upload the application on the phone you need only 6 steps:
1. The apk application can be found in the directory: Project name \ app \ build \ outputs \ *. apk
2. We connect the phone to the computer using a USB cable in the multimedia device mode so
that the computer can see the resources (files, catalogs) of the device.
3. We change the device settings so that you can install applications from sources other than
Google Play. Settings-> Security and select Unknown sources
4. We use the available Android file manager: Applications -> My Files -> All files or we use another
file manager, e.g. DropBox
5. We are losing the * .apk file from the computer to any directory on the device, using e.g.
Windows. You can also create a separate catalog for your own programs.
6. We are looking for our application on the phone, we install and run it.
run application on android device – way 2
run apk file in android device directly
To run the application on the phone you need only 3 steps:
1. check on mobile device setting in Programmers options
check box Debugging USB

2. set BuildType to debud in File\Projekct Structure\BuildType


for app

3. run the application on chosen mobile device

NOTE - this path may not be available due to


an incorrect USB cable
android – hardware – SMS
to programmatically receive and send an SMS, it is necessary to add in the AndroidManifest.xml
manifest permission to receive and send SMS by our program:

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>

also in the Manifest, in the <application> section we add SMS receiving actions

<receiver android:name="com.innovatio.pb
android:enabled="true">
.smskeeper.SMSListener"
<intent-filter android:priority=”123">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
android – hardware –SMS - example
Next, we add the SendMessageButton () SMS sending method after the OnCreate method.
while the SendMessageButton () method is called in the OnCreate method :

private void SendMessageButton() {


Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("123456789", null, "new SMS message", null, null);
Toast.makeText(MainActivity.this, "The message has been sent ",Toast.LENGTH_LONG).show();

} catch (Exception e) {
Toast.makeText(getApplicationContext()," Failed to send SMS ",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}); }
android – hardware –SMS - example
receiving SMS is a bit more difficult and based on the BroadcastReceiver class - the message receiver:
public class SMSListener extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Sender: "+ phoneNumber + ", Message: " + message , duration);
toast.show(); // <--- displaing the received message on the screen
}
}
} catch (Exception e) { Log.e("SmsReceiver", "Exception smsReceiver" +e); }
}
}
android – hardware –SMS
but this is not enough, you must add a local variable of the SMSListener class in the
MainActivity main class:

public class MainActivity extends Activity {


private SMSListener SMSReceiver;

and then use the constructor SMSReceiver = new SMSListener ();
the SMSReceiver object in the onCreate () main method.

it basically starts the listening session and when any message arrives, the onReceive
method from the SMSReceiver class will be started.
android – hardware - telephone
to make a program call, you must add permission to make calls and listen to the
phone status:

<uses-permission android:name="android.permission.CALL_PHONE" />


<uses-permission android:name="android.permission.READ_PHONE_STATE" />

and add the intention to connect:


Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:789643454"));
startActivity(callIntent);
android – hardware – telephone - example
calling can be done after pressing the buton:

button = (Button) findViewById(R.id.button1);


button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:678954322"));
startActivity(callIntent);
}
});
android – hardware – telefon
answering the phone programmatic is a bit more difficult, it requires creating a class:
PhoneCallListener inheriting from the PhoneStateListener class
And then use it e.g. in the onCreate method:

PhoneCallListener phoneListener = new PhoneCallListener();


TelephonyManager telephonyManager = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
android – hardware – photo camera
to operate the camera on Android you need:
add camera permission in the Manifest.xml manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
we add camera support variables in the main class:
- to switch from camera to videos
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;

- place where they will save photos and videos


private Uri fileUri
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
android – hardware – photo camera
in the onCreate method we add intentions to operate the camera:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //intent creation

and set the file save location


fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

and launch our camera


startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
android – hardware – photo camera
We add a preview image window and a button and support them in the main class in the
onCreate method, enter:

b1=(Button)findViewById(R.id.button);
iv=(ImageView)findViewById(R.id.imageView);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
android-hardware-photo camera-example
we are still creating a camera operation method - displaying the photo taken:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {


super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bp);
}

let's not forget to add a button and a control displaying ImageView in the main class
variables:
Button b1;
ImageView iv;
android-hardware-photo camera-example
We create a new method for video recording:
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

// we set the highest quality of recording


intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

// and run after saving


startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
android – hardware - photo camera
the camera requires additional permissions in the manifest:
to memory:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and recording sound:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
to view recorded videos, use the VideoView control
to this we add permanent camera support in the MainActivity main class:
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
and permanent video recording on the card:
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
android-hardware-photo camera-example
We add another method to play the recording:
private void playVideo() {
try {

videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());

// start recording
videoPreview.start();

} catch (Exception e) {
e.printStackTrace();
}
}
android –hardware - WIFI
To enable communication via a WIFI wireless network, it is necessary to set in the manifest permission
to access the network and read the network status:

<uses-permission android:name=“android.permission.ACCESS_NETWORK_STATE” />


<uses-permission android:name=“android.permission.ACCESS_WIFI_STATE” />
<uses-permission android:name=“android.permission.CHANGE_WIFI_STATE” />
<uses-permission android:name=“android.permission.CHANGE_WIFI_MULTICAST_STATE” />

and enabling WIFI functionality

<uses-feature android:name="android.hardware.wifi" />


android – hardware - WIFI
do samej komunikacji używamy odbiornika BrodcastReceiver W ten sposób możemy pobrać informacje o
wykrytych sieciach WIFI

private BroadcastReceiver mNetworkReceiver = new BroadcastReceiver(){


public void onReceive(Context c, Intent i){
Bundle b = i.getExtras();
NetworkInfo info =
(NetworkInfo) b.get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(info.isConnected()){
//program wykonywany po uzyskaniu połączenia
}else{
// program w przypadku nieudanej próby połączenia
}
}
};
android – hardware - WIFI
after detecting the WIFI network, we can establish a connection using methods from
the class

WifiManager :
addNetwork (WifiConfiguration config) - adds a new WIFI network
createWifiLock (String tag) - methods for connecting to a WIFI network
disconnect () - disconnect the connection to the WIFI network
getWifiState () - get the WIFI network status
isWifiEnabled () - checking the availability of the WIFI network
android – databases
SQLite - native database
MS SQL – SQL server database
FireBase - cloud base
android – native database - SQLite
the SQLite database is a native part of the system
XML database
we don't need JDBC or ODBC drivers to connect to the android database SQLite

important methods:
MyDatabase - constructor
onCreate - creating a database
executeSQL - execute any SQL command
Cursor - cursor on records read from the database
android – database SQLite
/* creating a database object */ import android.database.Cursor;
MyDatabase mydb = new MyDatabase(this);
/* reading data from the database to the cursor */

/* writing data to the database */ SQLiteDatabase db = this.getWritableDatabase();


String selectQuery = " select department_id,count(1),min(salary)
SQLiteDatabase db = getWritableDatabase(); from hr.employees ";
db.executeSQL(
Cursor c= db.rawQuery(selectQuery, null);
"insert into students(Name, Surname,
IndexNumber) values('John','Smith','GB23432');"
/* reading data from the cursor */
while (c.moveToNext()){
tv.append("\n" + c.getString(0) + " " + c.getString(1) + " " +
c.getString(2) + " " + c.getString(3) );
}
android – create a new database class
Let’s create a new class MyDatabase: File->New->Class Then we create the onCreate method in which we create tables using the SQL
command.
public class MyDatabase extends SQLiteOpenHelper {
@Override
} public void onCreate(SQLiteDatabase db)

db.execSQL(
/* necessary packages */ "create table students("
import android.database.sqlite.SQLiteDatabase; + "StudentId integer primary key autoincrement"
+ ", Name text"
import android.database.sqlite.SQLiteOpenHelper; + ", Surname text"
import android.content.Context; + ", IndexNumber text"
+");"
);
/*constructor*/
public MyDatabase (Contex context){ … and we should create the onUpgrade method to change the database
super(context, "students.db", null, 1); version:
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVerion, int newVersion){
}
android – create a new methods
then we add a method to the record to the database to the MyDatabase class:
public void AddStudent(String Name, String Surname, String IndexNumber){
SQLiteDatabase db = getWritableDatabase(); //handle to the database for writing ContentValues
student = new ContentValues();
student.put("Name", Name);
student.put("Surname", Surname);
student.put("IndexNumber",IndexNumber);
//db.insertOrThrow("students", null, student);
db.insert("students", null, student);
}
and we still lack the method to read the record from the database, which we also add to the MyDatabase class:
public Cursor getStudents(){
String[] collumns = {"StudentId", "Name", "Surname", "IndexNumber"};
SQLiteDatabase db = getReadableDatabase(); // handle to the database for reading
Cursor records = db.query("students", collumns, null, null, null, null, null );
return records;
}
android – database – use - writing
It's time to use our class to operate the database in the main class MainActivity.
At the class level, we declare a global variable:
MyDatabase mydb = new MyDatabase(this);
We add a button, EditText controls to enter the data we want to insert into the database.
In the onClick event, under the button we add support for saving a record from EditText
controls to our database.

EditText etNumber, etName;


etNumber = (EditText) findViewById(R.id.etNumber);
etName = (EditText) findViewById(R.id.etName);

String strNumber = etNumber.getText().toString();


String strName = etName.getText().toString();
mydb.AddStudent(strNumber, strName)
android – database – use - reading
To read records from the database, we can use the cursor.
To this end, we add the Cursor Package to read data from the database in the main
class MainActivity.java
import android.database.Cursor;
and the cursor itself is operated under the same onClick event:
//displaying records from the database;
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Lista Studentów:");
Cursor c = mydb.getStudents();
while (c.moveToNext()){
tv.append("\n" + c.getString(0) + " " + c.getString(1) + " " + c.getString(2) + " " + c.getString(3) );
}
android – database – use – data view
To make all records visible, we will add vertical scrollbar support in the TextView control.
To this end, we add the following lines in the activity_main.xml file in the textview definition:
android:maxLines = "10"
android:scrollbars = "vertical"

And under the declaration of the tv object we will add a method:

tv.setMovementMethod(ScrollingMovementMethod.getInstance());

and we will add the import of the ScrollingMovementMethod package:


import android.text.method.ScrollingMovementMethod;

In this way, we have realised the recording and reading of data from the database.
android – database - from another side
Data can also be added to the database directly using the SQL INSERT command using the execSQL
method.

mydb.execSQL ("INSERT INTO student (number, name) VALUES ('" + strNumber + "', '" + strName + "');");

The AddStudent and getStudents methods use constructor methods to return handles to the
getWritableDatabase () and getReadableDatabase () databases. Wherein getWritableDatabase () returns
points to an open database for writing records. However, if you only needed to read data from the
database, just use the getReadableDatabase () method.

It is also worth paying attention to the query method available for the SQLiteDatabase db object. This
method provides all the options of the select command from SQL, where we can use such derectives as
distinct, group by, order by, having etc.

There is also a rawQuery method that lets you execute SELECT commands in the form of a query:
android – database - from another side
There is also a rawQuery method that lets you execute SELECT commands in the form of a
query:

SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = " select department_id,count(1),min(salary) from hr.employees ";
Cursor c= db.rawQuery(selectQuery, null);

and reading data from the cursor is the same as for the query command:

while (c.moveToNext()){
tv.append("\n" + c.getString(0) + " " + c.getString(1) + " " + c.getString(2) + " " + c.getString(3) );
}
android – MS SQL database
connection class to connect to MS SQL Server:
ConnectionClass.java
public class ConnectionClass {
String ip = "192.168.0.100";
String classs = "net.sourceforge.jtds.jdbc.Driver";
String db = "Andro";
String un = "hitesh";
String password = "789";
}
ip - database server IP address
classs - class name with database driver
db - database name
un- user
NOTE: jdbc driver is required
android – database - from another side
The MyDatabase class created in this form is sufficient for basic database operation.
But let's add one more universal netoda that will allow us to perform any SQL command on
our basis:
public void executeSQL(String query ){
SQLiteDatabase db = getWritableDatabase();
db.execSQL( query );
}

We can add one record using the executeSQL method, which allows any SQL query to be
performed on our database:

mydb.executeSQL(
"insert into students(Name, Surname, IndexNumber) values('John','Smith','GB23432');"
);
android – MS SQL database - example
connection class - communication with the MS SQL
database:

@SuppressLint("NewApi")
public Connection CONN() { try {
StrictMode.ThreadPolicy policy = new Class.forName(classs);
StrictMode.ThreadPolicy.Builder() ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
.permitAll().build(); + "databaseName=" + db + ";user=" + un + ";password="
StrictMode.setThreadPolicy(policy); + password + ";";
Connection conn = null; conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
String ConnURL = null;
Log.e("ERRO", se.getMessage());
try } catch (ClassNotFoundException e) {
catch { Log.e("ERRO", e.getMessage());
... } catch (Exception e) {
} Log.e("ERRO", e.getMessage());
return conn; }
}
android – MS SQL – database - login
using the connection class:

connectionClass = new ConnectionClass();


edtuserid = (EditText) findViewById(R.id.edtuserid); - user
btnlogin = (Button) findViewById(R.id.btnlogin); - login
edtpass = (EditText) findViewById(R.id.edtpass); - password
pbbar = (ProgressBar) findViewById(R.id.pbbar); - progres
pbbar.setVisibility(View.GONE);
android – MS SQL - database- query
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.spinners);
connect = CONN(un, passwords, db, ip);
ip = "192.168.0.100";
stmt = connect.prepareStatement(query);
un = "sa";
rs = stmt.executeQuery();
passwords = "123"; ArrayList<String> data = new ArrayList<String>();
db = "MyDatabase";
spinnercountry = (Spinner) while (rs.next()) {
findViewById(R.id.spinnercountry);
String id = rs.getString("CountryName");
connect = CONN(un, passwords, db, ip);
data.add(id);
String query =
"select CountryName from countries";
}…
android – Firebase - cloud database
The firebase database support wizard is available from Android Studio
Menu->Tools->Firebase
android – Firebase - cloud database
connection to the Google Firebase cloud ->
we are creating a new project
android – Firebase - cloud database
steps:
connection to the Firebase cloud
adding a database to the application
permission configuration
write to the database
reading from the database
android – Firebase - cloud database
connection to the Firebase database requires the addition of
packages:
'Com.google.gms.google-services'
'Com.google.firebase: Firebase-database 9.2.1'
NOTE: the wizard will automatically suggest adding these
packages to the project

plus packages:
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
android – Firebase - cloud database
writing the value to the database:

FirebaseDatabase database = FirebaseDatabase.getInstance();


DatabaseReference myRef = database.getReference(„gps_position");
MyRef.setValue("51.244900, 22.534318");
android – Firebase - cloud database
reading data from Firebase:

myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
Toast.makeText(MainActivity.this,"Value is: " + value,Toast.LENGTH_LONG).show();

@Override
public void onCancelled(DatabaseError error) {
Toast.makeText(MainActivity.this,"Failed to read value, error " +
error.toException(),Toast.LENGTH_LONG).show();
}
});
android – Firebase - cloud database
Database address: https://console.firebase.google.com/project/gpsdatabase-7e754/database/data/

value view in database value view in application


Android - stores data in files
Is possible also stored data directly into files.
access to text files is the same as in other languages, we open the file, edit and save it:

FileInputStream fis = openFileInput(“file.txt”);


FileOutputStream fos = openFileOutput(“file.txt”, Context.MODE_WORLD_WRITEABLE);

operating on binary files still requires setting a file format or compression method:

FileOutputStream fos = openFileOutput(“image.png”,Context.MODE_WORLD_WRITEABLE);


bmp.compress(compress_image_format.PNG, 100, fos);
out.flush();
out.close();

but you can also read data directly from the stream :

InputStream is = this.getResource().openRawResource(R.raw.some_raw_file);
android – sensors
accelerometer
gyroscope
magnetic field
light
proximity
gesture sensor
temperature
barometer
android – sensors
necessary packages to support the sensors:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
list of all sensors used:
getSensorList()
control class, sensor support:
SensorManager
mSens = mSensorManager.getDefaultSensor (Sensor.TYPE _...);
important methods:
onSensorChanged ()
onAccuracyChanged () <- method required
onResume ()
OnPause ()
android – accelerometer
type:
TYPE_ACCELEROMETER

return values:
values[3] – acceleration in x, y axes, z in square meters per second

constant:
GRAVITY_EARTH, GRAVITY_JUPITER,
GRAVITY_MARS, GRAVITY_MERCURY,
GRAVITY_MOON, GRAVITY_NEPTUNE
android - gyroscope
type:
Sensor. TYPE_GYROSCOPE
return values:
values[] = matrix of device rotation in radians
constant:
without

NOTE: Conversion of radians to degrees value*180/PI


android – accelerometer vs gyroscope
accelerometer :
- detects linear movement well
- detects the slope well
- badly detects revs
- there is no difference between gravity and a linear shift
- vibration damping possible, but this introduces delays
gyroscope :
- measures all types of rotation
- does not measure offset
- possible suppression of hand shake

accelerometer + gyroscope = orientation in 3D space


android – orientation sensor
Typ:
TYPE_ORIENTATION
return value:
values [3] - rotation relative to the X, Y, Z axes clockwise, in degrees
android – light level sensor
type:
Sensor.TYPE_LIGHT
return value
values [0] = light level measured in lux
Constant:
- LIGHT_CLOUDY: 100
- LIGHT_FULLMOON: 0.25
- LIGHT_NO_MOON: 0.001
- LIGHT_OVERCAST: 10000.0 (cloudy)
- LIGHT_SHADE: 20,000.0
- LIGHT_SUNLIGHT: 110000.0
- LIGHT_SUNLIGHT_MAX: 120000.0
- LIGHT_SUNRISE: 400.0
android – proximity sensor
type:
Sensor.TYPE_PROXIMITY
return value:
values [0]: proximity measured in meters
android–temperature and pressure sensor
temperature:
type:
Sensor.TYPE_TEMPERATURE
return value:
values[0] = temperature in Kelvin(K) degrees

pressure:
type:
Sensor.TYPE_PRESSURE
return value:
values[0] = pressure in pascal (Pa)
android – magnetic field sensor
type:
Sensor.TYPE_MAGNETIC_FIELD

return value:
values[3] = magnetic field in X, Y and Z axes measured in uT

constants:
MAGNETIC_FIELD_EARTH_MAX: 60.0
MAGNETIC_FIELD_EARTH_MIN: 30.0
android –accelerometer – use - example
accelerometer use should start by adding the appropriate permissions to the manifest in the main
element:

<uses-feature android: name = "android.hardware.sensor.accelerometer" android: required = "true" />

the activity element should also block screen rotation, as this may cause an application error:

android: screenOrientation = "portrait„

then we import packages to support sensors:


import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
android –accelerometer – use - example
to use a sensor in a given class, we need to add SensorEventListener implements
so the class definition will look like this:
public class MainActivity extends Activity implements SensorEventListener {
...

add the sensor service manager variables in this class :

private SensorManager mSensorManager;


private Sensor mAccelerometer;

and add the service supporting the sensor in the OnCreate method, in our case the
accelerator type:
mSensorManager = (SensorManager) getSystemService (Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor (Sensor.TYPE_ACCELEROMETER);
android –accelerometer – use - example
then we add two methods:
onAccuracyChanged - responding to changes in sensor accuracy
onSensorChanged - reacting to the change of the measured value

NOTE: The first onAccuracyChanged method may be empty but must appear

@Override
public final void onAccuracyChanged (Sensor sensor, int accuracy)
{
// this method may be empty but must appear
}
android –accelerometer – use - example
The onSensorChanged method responds to the change of the measured value:

@Override
public final void onSensorChanged(SensorEvent event)
{
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];

TextView tvX = (TextView)this.findViewById(R.id.tvaX);


TextView tvY = (TextView)this.findViewById(R.id.tvaY);
TextView tvZ = (TextView)this.findViewById(R.id.tvaZ);

tvX.setText("X axis" + "\t\t" + x);


tvY.setText("Y axis" + "\t\t" + y);
tvZ.setText("Z axis" + "\t\t" + z);
}
android –accelerometer – use - example
finally, two more methods are needed to register sensor support: OnResume, OnPause
the setting the sensor reading frequency to SENSOR_DELAY_NORMA:

@Override
protected void onResume ()
{
super.onResume ();
mSensorManager.registerListener (this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause () {
super.onPause ();
mSensorManager.unregisterListener (this);
}
NOTE: SENSOR_DELAY_NORMA sensor reading frequency may turn out to be too fast for a given eye,
then you need to change to SENSOR_DELAY_UI
android –sensors list - example
to get a list of all sensors from your smartphone we need
to do:
1 - import packages:
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
android –sensors list - example
2- in the main activity class we declare variables:
SensorManager smm;
List <Sensor> sensor;
ListView lv;

we drag and drop the ListView control onto the window and we call it listView1
and linking with variable lv on the method onCreate :
lv = (ListView) findViewById (R.id.listView1);
android –sensors list - example
in addition in the onCreate method we add:

smm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);


sensor = smm.getSensorList(Sensor.TYPE_ALL);
lv.setAdapter(new ArrayAdapter<Sensor>(this, android.R.layout.simple_list_item_1, sensor));

if we want to display only the names and type of sensors, we must add:

/* displaying only the names and types of sensors */


List<String> sensor_list = new ArrayList<String>();
for(Sensor s : sensor) {
sensor_list.add(s.getName() + " " + s.getStringType());
}
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sensor_list));
android – google maps
generating the API_KEY key
markers
control on maps
view control
map types
android - google maps
to use maps in our program we must follow these steps:
install the Google Play service package
install Android SDK Build-tools, revision 20.0.0
create a project using Google maps
get the key - Google Maps API key
will add permission to use maps in the manifest
android - google maps - API key
to get the google map key:
open the google_maps_api.xml file
read the instructions contained in it:
paste the generated web request into the browser:
https://console.developers.google.com/flows/enableapi?apiid=maps_android_back
end&keyType=CLIENT_SIDE_ANDROID&r=98:FA:8A:4C:50:7A:F9:49:FF:V1:6E:8E:06:
AD:29:56:A4:BB:24:68%3Bcom.innovatio.pibednar.mymapapplication

NOTE: this is just a sample request, paste the


request from your own google_maps_api.xml
file into your browser
android – google maps - registration
after completing the generated request in the
browser, the registration console will appear using
the Google Developer Console
android – maps – API key generation
after accepting the terms, the
key generator appears. Click on
Create and a key appears that
we can use in our application.

this is what our generated key


will look like:
android – google maps – API KEY place
Having the key generated, we can add it to our application in place of:
API KEY to the google_maps_api.xml file in the resoureces section
<Resources>
<string name = "google_maps_key" templateMergeStrategy = "preserve"
translatable = "false"> API KEY </string>
</ Resources>
after inserting our key into the google_maps_api.xml file it will look like this:
<Resources>
<string name = "google_maps_key" templateMergeStrategy = "preserve" translatable = "false">
AIzAVSyAO-Ljjz_yPx7uFxxx7HRr </ string>
</ Resources>

NOTE: this sample key AIzAVSyAO-Ljjz_yPx7uFxxx7HRr must


be changed to your own.
android – google maps - emulator
Maps on devices that do not support Google Play
services will not start.
To make this possible, you should choose an
emulator with Google API support.
Android – google maps - manifest
and it was possible to use maps, add appropriate entries to the manifest:
in the main section of the manifest, add permission to use the location

<uses-permission android: name = "android.permission.ACCESS_COARSE_LOCATION" />


<uses-permission android: name = "android.permission.ACCESS_FINE_LOCATION" />

in the application section you should add meta data:

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/google_maps_key" />
android – google maps – use
With Google Maps Activity selected, a method supporting onMapReady maps is automatically created.
By default, this method sets the map position for Sydney, Australia.

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

// Add a marker in Sydney and move the camera


LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).
title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
android – maps - markers
correct operation of the program results in displaying a
map with the city of Sydney marked
the result on the device
the map is scalable
the marker is described (after clicking the marker)
the marker can be set anywhere, e.g. on Lublin by
modifying the onMapReady method accordingly
android – mapy - contol
the way the map is presented can be determined using the CameraPosition object:
static final LatLng lublin = new LatLng(51.245,22.570);

static final CameraPosition LUBLIN =


new CameraPosition.Builder().target(lublin)
.zoom(15)
.bearing(0)
.tilt(25)
.build();
using such defined object in the moveCamera method looks like this:

mMap.addMarker(new MarkerOptions().position(lublin).title(„Marker in Lublin"));


mMap.moveCamera(CameraUpdateFactory.newCameraPosition(LUBLIN));
android – gogle maps – current location
we add GPS position tracking permissions in the manifest:
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

and in MainActivity.java we add a method with the current GPS position collector - LOCATION_SERVICE:

private void setUpMap() {


LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
showCurrentLocationOnMap(location);
}
…}

android – gogle maps – current location
we call the requestLocationUpdates method in which we set the frequency of GPS polling, in
ms.:

locationManager.requestLocationUpdates(provider, 2000, 0, locationListener);


// Getting initial Location
Location location = locationManager.getLastKnownLocation(provider);
// Show the initial location
if(location != null)
{
showCurrentLocationOnMap(location);
}
}

Finally, you only have to add the showCurrentLocationOnMap method to set our current GPS
position on the map
android – gogle maps – current location
private void showCurrentLocationOnMap(Location location){
mMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet( location.getLatitude() + "'N " + location.getLongitude()+"'E")
.flat(true)
.title(„My current location"));
// zoom z dokładnością co do budynku
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 18));
}
android – google maps – view control
camera view settings: build - constructor
target - target, location
zoom scale: an example view definition will look like
1: the whole world this:
5: continents static final CameraPosition LUBLIN =
new CameraPosition.Builder()
10: cities
.target(lublin)
15: streets .zoom(20)
20: buildings .bearing(90)
bearing - orientation, map rotation .tilt(60)
.build();
tilt - angle of view
android – google maps – view control
we can activate controls on our map: we declare a variable
control lights, such as: private UiSettings mUiSettings;
zoom ...
compass
current position we set the visibility of controls on the map in
moving the map (by gestures) any method with map support:
zooming the map (by gestures) mUiSettings = mMap.getUiSettings();
angle adjustment (with gestures) mUiSettings.setZoomControlsEnabled(true);
rotating map (with gestures) mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(true);
mUiSettings.setScrollGesturesEnabled(true);
to do this, we need to import the package: mUiSettings.setZoomGesturesEnabled(true);
import com.google.android.gms.maps.UiSettings; mUiSettings.setTiltGesturesEnabled(true);
mUiSettings.setRotateGesturesEnabled(true);
android – google maps types
Google Maps provides us with 4 types of maps:
MAP_TYPE_NORMAL – road map
MAP_TYPE_SATELLITE – satellite map
MAP_TYPE_HYBRID - hybrid, road + satellite map
MAP_TYPE_TERRAIN – terrain map
the map type is set by the method: setMapType
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

You might also like