Android Notes

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 8

If you are ready with API key and device token you can use the below code

to send
push notification to a android device

try {
String androidFcmKey="XXXXXXXXXXXX";
String androidFcmUrl="https://fcm.googleapis.com/fcm/send";

RestTemplate restTemplate = new RestTemplate();


HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Authorization", "key=" + androidFcmKey);
httpHeaders.set("Content-Type", "application/json");
JSONObject msg = new JSONObject();
JSONObject json = new JSONObject();

msg.put("title", "Title");
msg.put("body", "Message");
msg.put("notificationType", "Test");

json.put("data", msg);
json.put("to", deviceToken);

HttpEntity<String> httpEntity = new


HttpEntity<String>(json.toString(),httpHeaders);
String response =
restTemplate.postForObject(androidFcmUrl,httpEntity,String.class);
System.out.println(response);
} catch (JSONException e) {
e.printStackTrace();
}

sender id :A unique numerical value created when you configure your API project.
The sender ID is used in the registration process to identify an app server that is
permitted to send messages to the client app.
Server key A key saved on the app server that gives the app server authorized
access to Google services. In HTTP, the server key is included in the header of
POST requests that send messages.

Application id : The client app that is registering to receive messages. How this
is implemented is platform-dependent:

Android: use the package name from the app manifest.


iOS: use the app's bundle identifier.
Chrome: use the Chrome extension name.

Registration Token An ID issued by the GCM connection servers to the client


app that allows it to receive messages. Note that registration tokens must be kept
secret.

android SDK manager

emulator to run our android app

android 2.2 covers most of all devices...

activity is nothing but section or page of your application..


activity can be home page or about page or we can say page of website, screen where
user interact
store in project folder @---android category folder , res --- layout folder
activity_main.xml

AVD manager --- android virtual device manager -- nexus5 to set default device

emulator HAXM required to run AVD

to solve this just run exe from the path of android sdk path having intel hardware
accelator

intelhaxm-android (2 gb)

geny motion emulator -- its FAST emulator

install geny motion plugin

studio has widgets

manifest folder -- main launcher having entry of all activities will have action
tag with acitivty package name

super class is activity

new activity will create activity xml and java file...

new java class called intent


create instance of intent
Intent intent = new Intent("activityname with package")
startActivity(intent) -- open acitivity by intent method

button_sbm = (Button) findViewById(R.id.button)

setOnClickListener(){
new View.OnClickListener(){
public void onClick(View v){
AlertDialog.Builder

just like message dialog or alert box in javascript

DialogInterface
}
}

resource has values folder to define string constants in strings.xml

drawable folder to store image asset


image type high dpi, mdpi,xhdpi,
layout /activity

setContentView(R.layout.activity_main)

ListView

adapter to add data to view

ArrayAdapter
seekbar -- progress bar

WebView -- like browser


webview.loadUrl(url)

android gestures..

android libraries --- android.view.MotionEvent


android.gesture.Gesture
android.view.GestureDetector

interface to implement MainActivity class ---


GestureDetector.OnGestureListener
GestureDetector.onDoubleTapListener
GestureDetectorCompat
onDoubleTap, onSingleTap

Android fragments ---


portion of UI on screen like portal...

layout linear layout, framelayout, table laoyout, relative layout


fragment manager help us to handle fragments

SQLite, a lightweight relational database, is used for data storage purposes.

Google Cloud Messaging (GCM) is a service that lets developers send short message
data to their users on Android devices,

core Android libraries available to the Android developer is as follows -


-----------------------------------------------------------------------
android.app - Provides access to the application model and is the cornerstone
of all Android applications.

android.content - Facilitates content access, publishing and messaging between


applications and application components.

android.database - Used to access data published by content providers and


includes SQLite database management classes.

android.opengl - A Java interface to the OpenGL ES 3D graphics rendering API.

android.os - Provides applications with access to standard operating system


services including messages, system services and inter-process communication.

android.text - Used to render and manipulate text on a device display.

android.view - The fundamental building blocks of application user interfaces.

android.widget - A rich collection of pre-built user interface components such


as buttons, labels, list views, layout managers, radio buttons etc.

android.webkit - A set of classes intended to allow web-browsing capabilities


to be built into applications.

Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed
and optimized for Android.
Android framework includes the following key services -

Activity Manager - Controls all aspects of the application lifecycle and


activity stack.

Content Providers - Allows applications to publish and share data with other
applications.

Resource Manager - Provides access to non-code embedded resources such as


strings, color settings and user interface layouts.

Notifications Manager - Allows applications to display alerts and notifications


to the user.

View System - An extensible set of views used to create application user


interfaces.

components are loosely coupled by the application manifest file AndroidManifest.xml


that describes each component of the application and how they interact.

4 main component of application:

Activities : They dictate the UI and handle the user interaction to the smart phone
screen.
Services: They handle background processing associated with an application.
Broadcast Receivers: They handle communication between Android OS and applications.
Content Providers: They handle data and database management issues.

Activity performs actions on the screen. For example, an email application might
have one activity that shows a list of new emails, another activity to compose an
email, and another activity for reading emails.

A service is a component that runs in the background to perform long-running


operations.
public class MyService extends Service {
}

public class MyReceiver extends BroadcastReceiver {


public void onReceive(context,intent){}
}

A content provider component supplies data from one application to others on


request.
public class MyContentProvider extends ContentProvider {
public void onCreate(){}
}

fragments, views, layouts, intents, resources, manifest...

select the form factors your application runs on, here need to specify Minimum SDK,
in our tutorial, I have declared as API23: Android 6.0(Mashmallow) -- target
android devices...

MainActivity.java source file having an activity class that runs when your app is
launched using the app icon.

layout/
XML files that define a user interface layout. They are saved in res/layout/ and
accessed from the R.layout class.

A service is a component that runs in the background to perform long-running


operations without needing to interact with the user and it works even if
application is destroyed. A service can essentially take two states -

content provider component supplies data from one application to others on


request....ContentResolver class....

defined content provider URI address which will be used to access the content...
content://contacts/people/5

SQLite database

Finally register your Content Provider in your activity file using <provider> tag.

// Add a new student record


ContentValues values = new ContentValues();
values.put(StudentsProvider.NAME,
((EditText)findViewById(R.id.editText2)).getText().toString());

values.put(StudentsProvider.GRADE,
((EditText)findViewById(R.id.editText3)).getText().toString());

Uri uri = getContentResolver().insert(


StudentsProvider.CONTENT_URI, values);

Toast.makeText(getBaseContext(),
uri.toString(), Toast.LENGTH_LONG).show();

on retrieve
String URL = "content://com.example.MyApplication.StudentsProvider";
Uri students = Uri.parse(URL);
Cursor c = managedQuery(students, null, null, null, "name");

if (c.moveToFirst()) {
do{
Toast.makeText(this,
c.getString(c.getColumnIndex(StudentsProvider._ID)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
}
}

A fragment has its own layout and its own behaviour with its own life cycle
callbacks.
create fragments by extending Fragment class and You can insert a fragment into
your activity layout by declaring the fragment in the activity's layout file, as a
<fragment> element.

fragment give more flexibiilty. divide device screen and control different parts
separately.
broadcastIntent to send it to any interested BroadcastReceiver components
an Intent object, is a passive data structure holding an abstract description of an
operation to be performed.

let's assume that you have an Activity that needs to launch an email client and
sends an email using your Android device. For this purpose, your Activity would
send an ACTION_SEND along with appropriate chooser, to the Android Intent Resolver

ACTION_SEND intent is to send an email..

assume that you have an Activity that needs to open URL in a web browser on your
Android device. For this purpose, your Activity will send
ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given URL in the
web browser.

String q = "tutorialspoint"
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);

Intent email = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));


email.putExtra(Intent.EXTRA_EMAIL, recipients);
email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
email.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
startActivity(Intent.createChooser(email, "Choose an email client from..."));

mechanisms for delivering intents to each type of component - activities, services,


and broadcast receivers.

An Intent object is a bundle of information which is used by the component that


receives the intent as well as information used by the Android system

intent is passed to startActivity, startService, sendBroadcast()


action -- mandatory part of an intent object

important Android Intent Standard Actions


ACTION_CALL_BUTTON -- to go to dialer or appropriate UI for placing a call

ACTION_CAMERA_BUTTON -- camera button was presseds

ACTION_DIAL: Dial a number as specified by the data.

ACTION_GTALK_SERVICE_DISCONNECTED

A GTalk connection has been disconnected.

ACTION_INSTALL_PACKAGE : Launch application installer.


ACTION_SEND:
Deliver some data to someone else.

View is the base class for widgets, which are used to create interactive UI
components like buttons, text fields, etc.

you can declare your layout using simple XML file main_layout.xml which is located
in the res/layout folder of your project.

A View is an object that draws something on the screen that the user can interact

Toast class provides a handy way to show users alerts but problem is that these
alerts are not persistent
flashes for few seconds...

simple way to create a notification.


As a first step is to create a notification builder using
NotificationCompat.Builder.build().
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");

Attach Actions to notifications so when user clicks on notification it will dirctly


go to activity in your application.
action is defined by a PendingIntent

pass the Notification object to the system by calling NotificationManager.notify()


to send your notification

layout file for new activity

location tracking, geofencing, and activity recognition.

Location object represents a geographic location which can consist of a latitude,


longitude,

location client which is LocationClient object, connect it to Location Services


using connect() method, and then call its getLastLocation() method. This method
returns the most recent location in the form of Location object that contains
latitude and longitude coordinates

callback method is called when location service is connected to the location client
successfully. You will use connect() method to connect to the location client

Geocoder.getFromLocation() method to get an address for a given latitude and


longitude

SmsManager smsManager = SmsManager.getDefault();


smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

or
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

smsIntent.putExtra("address" , new String("0123456789;3393993300"));


smsIntent.putExtra("sms_body" , "Test SMS to Angilla")
startActivity(smsIntent);
finish();

Intent phoneIntent = new Intent(Intent.ACTION_CALL);


phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));
startActivity(callIntent);

Intent callIntent = new Intent(Intent.ACTION_CALL);


callIntent.setData(Uri.parse("tel:0377778888"));
Android application publishing is a process that makes your Android applications
available to users. Infect, publishing is the last phase of the Android application
development process.
maximum size for an APK published on Google Play is 50 MB. can have extension file
if size is bigger.

Dx tools(Dalvik executable tools ): It going to convert .class file to .dex


file. it has useful for memory optimization and reduce the boot-up speed time
AAPT(Android assistance packaging tool):it has useful to convert .Dex file
to.Apk
APK(Android packaging kit): The final stage of deployment process is called
as .apk.

Build ? Generate Signed APK from your Android studio

You might also like