Fichas
ITECH3107 - Mobile Device Programming
Fichas del conjunto (118)
- 1AndroidAndroid is an OS developed by Google for mobile phones and other devices
- 2SDKSoftware Development Kit
- 3Android Stack1. - Apps
2. Java API Framework
3. Libraries and Android Runtime (ART)
4. Hardware Abstraction Layer (HAL)
5. Linux Kernel - 4AppsSystem and User Apps
- 5Java API Frameworkdeveloper Features
UI Components
resource Management
Lifecycle Management - 6Libraries and Android Runtime (ART)Each app runs in its own ART
Core system services are built from native through the API Framework - 7Hardware Acceleration Layer (HAL)Exposes device hardware capabilities
Camera
Bluetooth
Higher-level API - 8Linux KernelFoundation of Android
Manages threading
Low-level memory management
security - 9Challenges Developing AndroidBuilding for a multiscreen world
Maximizing app performance
Keeping your code and users secure
Making sure your app is compatible with older platform versions - 10The development process1. Create Project
2. Define Layouts
3. Write Code
4. Build and Run
5. Test and debug
6. Publish - 11GradleThis folder contains all the files needed by the build system
Specified additional libraries - 12ViewsHierarchy of objects
- 13Types of ViewsText View - For Text
EditText - For entering and editing text
Clickable- Buttons, Radio
ScrollView and RecyclerView - Scroll items
Imageview for displaying image
ConstraitLayout and LinearLayout - for containing and position other views - 14Week 2Week 2
- 15ActivityRepresents a single screen in an app
- 16Manifest.xmlAll activities must be declared in the manifest file
Package name
App components of the app services or activities
Permissions the app needs
Hardware or software features the app requires - 17Activity StatesCreated
Started (Visible)
Resumed
Paused
Stopped
Destroyed - 18onCreateWhen the activity is created for the first time
This is the only required callback
It stays in this state until the app is fully started (Ran all the code) - 19onStart()After onCreate()
Called if the stopped activity is called back
Can be called many times
Similar to created only stays in this state for the duration of the code running in the callback - 20onResume()Once the app has been initialized is ready to use
Running state
Use with OnResume and OnPause
If the app is in the foreground it will be in this state - 21onPause()Activity goes into the background
Only partially visible
Split-screen mode
Stop any services running
Nothing CPU intensive - 22onStopNo longer visible on the screen either because the new app has been started or they have returned to home screen
Will still retain the app
Use onStop to save persistent data and release any resources not released in onPause - 23onDestroyShut down completely
Finish method is called
Fully clean up and resources
Don't rely on this method to save data as it may be called unexpectedly - 24onRestartThe app is restarted from stopped state
- 25Events that cause apps to get destroyedUse Navigates Back
System Configuration Change - 26IntentEach activity in android is started or activated with an intent.
Message object that requests android runtime to start
Build your own intent within your activity to start another activity - 27Intent TypesExplicit Intents
Implicit Intents - 28Explicit IntentsYou specify the receiving activity using the activities class name.
E.g. Moving between screens in your app - 29Explicit Intents CodeIntent messageIntent = new Intent(this, ShowMessageActivity.class);
startActivity(messageIntent);
Arguments:
Application Context (This)
Which class to start (ShowMessageActivity.class) - 30Implicit IntentsYou do not specify a specific activity or component to receive the intent
For example if you have multiple camera apps on your phone the app may ask which one you would like to use - 31Passing Data with Explicit IntentsUsing extras to send your data within the intent
When receiving you get the intent object the activity was started with and retrieve extras - 32Intent DataOnly one piece of information
Usually a URI like a website or telephone number
messageIntent.setData(Uri.parse("http://www.google.com"));
Setdata will overwrite the data - 33Intent ExtrasDetermine the keys for each bit of information
Use the Puteextra method
Some intent extras are already provided but most times better to create your own type
SENDING EXTRA
messageIntent.putExtra(EXTRA_MESSAGE, "this is my message");
GETTING EXTRA
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); - 34startActivityForResult()Start this method with a request code
create a new intent in the launched activity and add the return data to that intent
onActivityResult() in the original activity - 35startActivityForResult() ExamplestartActivityForResult(messageIntent, 3);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) {
if (resultCode == RESULT_OK) {
String reply =
data.getStringExtra(SecondActivity.EXTRA_RETURN_MESSAGE);
// process data
}
}
} - 36Implicit Intent ExampleIntent sendIntent = new Intent();
NEW ACTION:
Intent sendIntent = new Intent(Intent.ACTION_VIEW); - 37Showing App Chooser// The implicit Intent object
Intent sendIntent = new Intent(Intent.ACTION_SEND);
// Always use string resources for UI text.
String title = getResources().getString(R.string.ch_title);
// Create the wrapper intent to show the chooser dialog.
Intent chooser = Intent.createChooser(sendIntent, title);
// Resolve the intent before starting the activity
if (sendIntent.resolveActivity(getPackageManager()) != null) {
startActivity(chooser);
} - 38Dalvik Virtual MachineThis is what android apps are translated into
When running on the Dalvik Virtual Machine or ART - 39Dalvik Virtual MachineDalvik is a register-based virtual machine
A stack-based VM must transfer data from registers to the operand stack before manipulating them.
A special process called the Zygote is launched when android initially boots - 40ZygoteStarts a virtual machine
Loads the core libraries and starts various shared structures - 41Event-Driven ProgrammingAndroid apps
Events go in a message queue and handled in order
This causes a potential problem of one task delaying all of them - 42Make an app respondCreate a Listener Object
Implement a Handler - 43ThreadingThe main thread is generally only used for UI work
This is why we create other classes and use these in an AsyncWay - 44ThreadingEach app starts with a single thread
This thread is known as the main or UI thread which deals with received events - 45Basic ConcurrencyCreate a new Thread
Override its run()
Call Start() - 46Week 3Week 3
- 47Looper ClassLoops forever waiting for messages which it pots to its handler
Loop() method - 48Manipulating Android UICan only be done from main activity or UI thread
- 49AsyncTaskDoesn't occur at the same time
Abstract Class which means we cannot directly create an object of this type - 50AsyncTask Methodsprotected void onPreExecute()
Runs to completion on the main thread before the main task starts
protected Result doInBackground(…)
Starts the task on a separate thread.
protected void onProgressUpdate(…)
Runs on the main thread and triggered when there has been an update to the task. This allows us to update the UI (i.e. the user) about task progress.
protected void onPostExecute(Result result)
Runs on the main thread and allows us to post-process our result.
protected void onCancelled(Result result)
Runs on main thread and allows us to display or clean up on cancel. - 51AsyncTask CaveatsSingle Use Object
Once started it can never be started again
however, you can create a new instance of it
MyAsyncTask task = new MyAsyncTask(); - 52AsyncTask Feedback Loading BarUse a ProgressDialog
onProgressUpdate()
progress.setProgress(0); - 53Canceling TasksTo do so, we must:
Set setCancelable(true) on our ProgressDialog,
Provide a OnCancelListener which itself provides an onCancel method which cancels the task, and
Check whether the task isCancelled() inside the loop of our doInBackground() method. - 54AsyncTask is deprecatedAsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.
- 55Runnable Vs ThreadsRunnable is an interface - we provide a run() method to perform some task, and multiple threads can access it.
Thread is a class, and as such it creates an object that can carry out a task. But only that thread can access the task. - 56PersistenceRAM is volatile (Lost on power loss)
Android provides 4 ways to persist data:
- Shared Preferences
- Files
-SQLite Databases
- Storing on a network - 57Persistence Methods ExplainedShared Preferences Store private primitive data in key-value pairs.
Internal Storage Store private data on the device memory.
External Storage Store public data on the shared external storage.
SQLite Databases Store structured data in a private database.
Network Connection Store data elsewhere on some form of server. - 58Shared PreferencesThe general framework that allows you to save and retrieve persistent key-value pairs of primitive data types
No specifically for saving user preference
PreferenceActivity is more for saving user preference - 59Shared Preferences Example// We need an Editor object to make preference changes.
SharedPreferences.Editor editor = getSharedPreferences(PREFS_FILENAME, MODE_PRIVATE).edit();
// Update our user's preference values with the latest values // the user has entered into the UI
// - Favourite Colour
EditText tempET = findViewById(R.id.faveColourET);
faveColour = tempET.getText().toString();
// - Favourite Number
tempET = findViewById(R.id.faveNumberET);
faveNumber = Integer.valueOf( tempET.getText().toString() ); - 60File Access ModesMODE_PRIVATE - Means only this app can access that file
MODE_APPEND - File will be created with read/write permissions for the creating application - New details will be appended to existing file - 61Writing file to internal storageCall openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.
Write to the file with write().
Close the stream with close(). - 62Writing file to internal storage Example// FileOutputStream (saving contents) try (FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE) ) { // Write the string to the file using the getBytes() method fos.write( faveColour.getBytes() ); fos.write( NEW_LINE.getBytes() ); fos.write( faveNumber.toString().getBytes() ); fos.write( NEW_LINE.getBytes() ); fos.write( Boolean.valueOf(silentMode).toString().getBytes() ); fos.write(NEW_LINE.getBytes()); } catch (FileNotFoundException fnfe) { Log.e(TAG, fnfe.getMessage()); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage()); }
- 63Reading file from internal storage Example// Assuming we were able to read file okay, then update the // layout with the file details // - Favourite Colour EditText tempET = (EditText) findViewById(R.id.faveColourET); tempET.setText(faveColour); // - Favourite Number tempET = (EditText) findViewById(R.id.faveNumberET); tempET.setText(faveNumber.toString()); // - Silent Mode CheckBox cb = (CheckBox) findViewById(R.id.silentModeCB); cb.setChecked(silentMode); } catch (FileNotFoundException fnfe) { Log.e(TAG, fnfe.getMessage()); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage()); } } // End of readInternalFile() method
- 64Check Media Availability// If it's either MEDIA_MOUNTED or MEDIA_MOUNTED_READ_ONLY...
if ( state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY) ) - 65Type of FilesPublic Files - Available to other apps
Private Files - Only belong to your app - 66Array AdapterAn Array Adapter is something that knows about an array, and how the type of values in that array should be drawn or displayed.
Returns array as a view
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, fruit); - 672 SQLite Classesandroid.database.sqlite.SQLiteOpenHelper
android.database.sqlite.SQLiteDatabase - 68SQL Helper ClassGive Database Name
Database Version
Create Database with already made data
Write in SQL - 69CursorsNavigate through a set of results returned from querying a database
Cursor shows us where in the results we are - 70ContentValuesContentValues objects are used to insert data into the database.
- 71Networking PermissionsIf you want your app to connect to the internet you need permissions
- 72HTTP ClientsAndroid has 2
HttpURLConnection
Apache HttpClient. - 73Networking ThreadsNetworking can have an unpredictable delay
and should be performed with an Asynctask - 74Bluetooth Permissions
- 75Bluetooth 4 major tasksSetting up Bluetooth,
Finding devices that are either paired or available in the local area
Connecting devices
Transferring data between devices. - 76getBondedDevices()Getting any connected devices information
- 77Sensor TypesMotion Sensors - Accelerometer
Environmental Sensors - Temperature
Position Sensors - Magnetometers - 78Sensor APIGet a list of sensors on the device
Individual sensor ability
Utilize data from the sensor - 79Sensor TypesHardware - Physical component
Software-Based - 80Sensor FrameworkSensorManager - Use this class to create an instance of the sensor service it also provides methods for accessing sensors
Sensor Class - Functional on individual sensor
SensorEvent - When the sensor provides information
SensorEventListener - You can use this to get sensor values or when senior changes - 81Sensor WorkflowIdentifying sensors and sensor capabilities
Monitor sensor events - 82GeocodingConverting a string representing a location to a location on the map is known as geocoding using a geocoder object
- 83Location PermissionsACCESS_COARSE_LOCATION, and
ACCESS_FINE_LOCATION. - 84LocationManagerThe first parameter is the preferred provider
Second parameter is minTime
Third is minDistance
The fourth parameter is locationListesner - 85GeoFencingcombines awareness of the user's current location with awareness of nearby features, defined as the user's proximity to locations that may be of interest.
- 86Security DefinitionResistance to Harm
- 87Security Law 1If a bad guy can persuade you to run their program on your computer its, not your computer anymore
- Keylog
- Document Security
- Fake your identity - 88Security Law 2If a bad guy can alter the operating system on your computer, it's not your computer anymore
- OS Files are the most trusted on the computer
- Manage User Accounts - 89Security Law 3If a bad guy has unrestricted physical access to your computer, it's not your computer anymore
- Unplug
- Break
- Tamper
- Install Software - 90Security Law 4If you allow a bad guy to upload programs to your website, it's not your website any more
- Running a program on your website - 91Security Law 5Weak passwords trump strong security
- Use Passwords
- Fake Being You
- - 92Security Law 6A computer is only as secure as the administrator is trustworthy
- Untrustworthy Admin
- Modify System
- Add Bogus Users
- Install Virus - 93Security Law 7Encrypted data is only as secure as the decryption key
- 94Security Law 8An out of date virus scanner is only marginally better than no virus scanner at all
- 95Security Law 9Absolute anonymity isn't practical, in real life or on the Web
-VPN
- Use Public Computers
- Tor - 96Security Law 10Technology is not a panacea
Pancea: a solution or remedy for all difficulties or diseases.
It will never be 100% safe - 97Big Security Viruses in PastHeartbleed
ShellShock - 98Security PrinciplesMinimize Attack Surface
Establish Secure Defaults
Least Privilege
Defense in Depth
Fail Securely
Don’t Trust Services / Infrastructure
Separation of Duties
Avoid Security by Obscurity
Keep Security Simple
Fix Security Issues Correctly - 99Mobile SecurityThis varies from ordinary security
Mobile phones hold a lot more personal data and can access to payments and banks - 100Android Security 1Minimise Attack Surface
The more features you have the more can be based - 101Android Security 2Establish Secure Defaults
For example, log out users on the exit of app
Always choose the encrypted way - 102Android Security 3Least Privilege
minimum permissions required - 103Android Security 4Defence in Depth
Robust linux kernel
Application Signing
Asking for permissions - 104Android Security 5Fail Securely
User Generic Error Messages
Use Global Exception Handlers - 105Android Security 6Don't Trust Services / Infrastructure
Check SEcurity Certificates
Ensuring that we use encrypted connections
Dont provide data not necessary - 106Android Security 7Separation of Duties
- 107Android Security 8Avoid Security through Obscurity
do not use backdoors
no debug messages - 108Android Security 9Keep Security Simple
Write code carefully - 109Android Security 10Fix Security Issues Correctly
SImple code
Fix thinks properly - 110What is performance- No large delays
Everything working
- Limited resources on a phone - 111What is Optimisation- Rewriting messy code
- Take out code - 112Performance Tuning stepsAssess the problem
Measure the performance
Identify the bottleneck
Modify the bottleneck code
Measure performance
Adopt the new code if it helps - 113Performance AnalysisAlso called profiling
which sections of a program to optimize.
Find
Hotspots - Which are pieces of code that run most often
Bottlenecks - 11490/10 law90% of your program's execution time will be spent running 10% of your code
identify this with a profiler - 115Big O notationBig O notation, represents an upper bound on the complexity of an algorithm
In case you were wondering ‘O’ stands for omicron - 116PoolsPerform the expensive set-up just once, then
Re-use the system/connection we’ve set up as required, and finally
Tear down the system/connection at the end when we’re finished. - 117Static over VirtualIf you don't need to access an object's fields in a method, make your method static.
- 118—
Información
- Descripción
- Fichas sobre ITECH3107 - Mobile Device Programming, creado por Ash Z el 09/06/2020.
- Creado por
- Ash Z
- Visitas
- 2
- Valoración