Android Core Basic Learning process

Source: Internet
Author: User
Tags message queue xml parser

First day:
ADB command:
ADB devices List of all devices
ADB shell mounts to Linux space and can execute Linux commands
ADB install xxx.apk If multiple devices adb install-s device name
ADB push pushes files to the phone
ADB pull pulled the file out of the phone
Netstat-ano Viewing port numbers
Taskkill/pid pid/f kills PID corresponding process
Phone Dialer
1. Locate the control and get the control object
Et_phone = (EditText) Findviewbyid (R.id.et_phone);
Button Bt_call = (button) Findviewbyid (R.id.bt_call);
2. Set the Click event for the button and get the value entered by the user in the text box.
String phone = Et_phone.gettext (). toString (). Trim ();
3. Create an intention to make a call and turn on
Intent Intent = new Intent ();
Set up an action to dial a phone number
Intent.setaction (Intent.action_call);
Set the dialed phone number
Intent.setdata (Uri.parse ("tel://" +phone));
Turn on the intention to make a call
StartActivity (Intent);
Four Click events
1, the use of internal class way to achieve Onclicklistener
2. Using Anonymous internal classes
3, let the current class to implement Onclicklistener, and implement the method is not implemented
4, define the OnClick method in the button of the layout file, and implement the corresponding method in the code.
Standard: public void XXX (view view) {}

Day two:
1. JUnit test methods
Write a test class to inherit the Androidtestcase class
Adding in the manifest file
<!--Add the instruction set to the manifest node, and the command assembly deploys the application to the emulator to run
<instrumentation android:name= "Android.test.InstrumentationTestRunner"
Android:targetpackage= "Com.itheima.junit" >
</instrumentation>
<!--add JUnit test packages to the application node--
<uses-library android:name= "Android.test.runner"/>
2. Read the data from the file and display it to the control
1. Save the file to the SD card
File File = new file (Environment.getexternalstoragedirectory (), "xx.txt");
FileOutputStream fos = new FileOutputStream (file);
Fos.write ("xxx". GetBytes ());
Fos.close ();
2. read files from SD card
File File = new file (Environment.getexternalstoragedirectory (), "xx.txt");
FileReader FR = new FileReader (file);
BufferedReader br = new BufferedReader (FR);
String info = br.readline ();
3. Add access to the SD card in the manifest file
Write SD card
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
Read SD card
<uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/>
3. Sharedpreferences store and read data
Save data
Sharedpreferences sp = getsharedpreferences ("xxx", 0);
Sp.edit.putString ("Key", "Value"). Commit;
Reading data
String data = sp.getstring ("Key", "Default value");
4. Creation and parsing of XML files
1. Create an XML file
1. Initializing a serializer for an XML file
XmlSerializer serializer = Xml.newserializer ();
2. Initialization of the sequencer parameters
File File = new file (Environment.getexternalstoragedirectory (), "Backup.xml");
FileOutputStream fos = new FileOutputStream (file);
Serializer.setoutput (FOS, "UTF-8");
3. Start writing the XML file.
Serializer.startdocument ("UTF-8", true);
Serializer.starttag (NULL, "SMSS");
Start writing Body node
Serializer.starttag (NULL, "body");
Serializer.text (Info.getbody ());
Body Node End
Serializer.endtag (NULL, "body");
SMSS root node End
Serializer.endtag (NULL, "SMSS");
XML end
Serializer.enddocument ();
Fos.close ();
2. Parsing XML files
/**
* Parse the data returned by the server to get weather information
* @param the stream containing weather information returned by the IS server (XML)
* @return
*/
public static list<channel> Getallweatherinfos (InputStream is) throws exception{
List<channel> channels = NULL;
Channel channel = NULL;
1. Get the XML parser
Xmlpullparser parser = Xml.newpullparser ();
2. Setting parameters for the XML parser
Parser.setinput (IS, "utf-8");
3. Start parsing the XML file.

int type = Parser.geteventtype ();//Gets the type of the current event
while (type!=xmlpullparser.end_document) {//need to have the pull parser resolve to the end of the file
Switch (type) {
Case Xmlpullparser.start_tag:
if ("Weather". Equals (Parser.getname ())) {//Total start node
Channels = new arraylist<channel> (); Initializing a Collection
}else if ("Channel". Equals (Parser.getname ())) {//A city's information begins.
Channel = new channel ();
Gets the attribute value to the ID
String id = parser.getattributevalue (0);
Channel.setid (Integer.parseint (id));
Parse City node
}
Break
To determine the end node of an XML
Case Xmlpullparser.end_tag:
if ("Channel". Equals (Parser.getname ())) {
Add the parsed content to the collection
Channels.add (channel);
channel = null;
}
Break
}
Type = Parser.next ();
}
Is.close ();
Return channels;//The collection of all the channels back
}
Day Three:
1. Steps to create a database
To create a class inheritance Sqliteopenhelper
Create a database
DBHelper helper = new DBHelper (This, "account.db", NULL, 1);
OnCreate is called when the database is created and is used primarily to initialize the data table structure and insert data initialization records
Onupgrade is called when the database version is upgraded, mainly to change the table structure
1. Inserting data
Contentvalues values = new Contentvalues ();
Values.put ("name", "Zhangsan");
Long rowId = Db.insert ("person", null, values);
2. Query data
cursor cursor = db.query ("Person", new string[]{"id", "name"}, NULL, NULL, NULL, NULL, NULL);
while (Cursor.movetonext ()) {
int id = cursor.getint (0);
String name = cursor.getstring (1);
System.out.println ("id=" +id+ "; name=" +name);
}
3. Update data
Contentvalues values = new Contentvalues ();
Values.put ("name", "Wangwu");
Db.update ("person", Values, "id=", New string[]{"1"});
4. Delete data
Db.delete ("Person", "id=", New string[]{"2"});
2, the use of the ListView
1. Get the ListView Object
2, Lv.setadapter (new Myadapter ()) Fill data
3. Create a class to inherit baseadapter and implement a method that is not implemented
Mainly GetCount and GetView.
TextView tv_id = (TextView) View.findviewbyid (r.id.tv_id);
TextView tv_name = (TextView) View.findviewbyid (r.id.tv_name);
Person P = list.get (position);
Tv_id.settext (P.getid () + "");
Tv_name.settext (P.getname ());
return view;
Day Fourth:
1. Network Picture Viewer
1. Send Request
1. Create a URL object
URL url = new URL (path);
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
2. Set the request header information
Conn.setrequestmethod ("GET");
Conn.setconnecttimeout (3000);
2. The server returns data
1, judge the status code of ok,404 No resources found, 503, 509 server-side error
Conn.getresponsecode ();
2, parsing the binary data returned by the server
InputStream is = Conn.getinputstream ();
String data = Streamtools.readstream (IS);
3. Display the picture on the control
Message msg = Message.obtain ();
Msg.obj = data;
Handler.sendmessage (msg);
Private Handler Handler = new Handler () {
public void Handlemessage (Android.os.Message msg) {
String data = (string) msg.obj;

Tv_content.settext (data);
};
};
4. Add permission to access the Internet:
<uses-permission android:name= "Android.permission.INTERNET"/>
2. Thread cannot modify UI interface
The OnCreate method in activity and the method of click event are all running in the main thread
Only the thread creating the UI interface can modify the UI only the original thread, created a view hierarchy can touch its views.
Main thread (UI thread): Only the main thread can modify the UI, and if the child thread modifies the UI, the system verifies that the current thread is not the thread and, if it is not the main thread, terminates the run
Runonuithread
3, the principle of message processing mechanism
Steps:
1. Create handler in main thread
Private Handler Handler = new Handler () {};
2. Get handler reference in thread, call method of sending message
Message msg = new Message ();
Msg.obj = BM;
Handler.sendmessage (msg);
3. Handler Modify UI Interface
public void Handlemessage (Message msg) {
Super.handlemessage (msg);
2. Handler Modify UI Interface
Bitmap BM = (Bitmap) msg.obj;
Iv.setimagebitmap (BM);
}
Handler, message, Looper (the principle of the messaging mechanism):
Prerequisite knowledge
All operating systems that use the UI interface run a dead loop in the background, constantly monitoring and accepting instructions from the user and executing them as soon as they are accepted
When the process of our Android application is created, the system gives the process a looper
Looper is a dead loop that internally maintains this message queue, loops continuously cancels messages from the message queue, sends the message to handler, and finally handler modifies the UI based on the received message.

4. Submit data Using POST method
Business Scenario:
1. User Login
2. File Upload
1, set the request header information post, Content-length:
Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");
Two request header information that must be added
Conn.setrequestproperty ("Content-length", data.length () + "");
Conn.setrequestmethod ("POST");
2, set the data submitted to the server side:
Conn.setdooutput (TRUE);
Write the data to the server side
Conn.getoutputstream (). Write (Data.getbytes ());
Disadvantages:
1. Complex code
Advantages:
1, security;
2, submit a large number of data
Day Fifth:
1, using POST method to submit data is Chinese garbled solution
Workaround: Use character set encoding on both sides of the client and server for consistency. UTF-8,
2, using get method to submit data in Chinese garbled solution
Use Urlencoder.encode (name, "UTF-8") for URL encoding:
String Path = "Http://192.168.22.136:8080/web/servlet/LoginServlet?username=" +urlencoder.encode (name, "UTF-8") + " &password= "+urlencoder.encode (pwd," UTF-8 ");
3.
Day Sixth:
1. Difference between explicit and implicit intentions
You can only open the interface in your application
Implicit intent to open the interface of another application
2, the purpose of the design intent
Decoupling to achieve high cohesion and low coupling of applications. Ensure that applications can run independently from each other and can call each other
Make sure you write your own code to reuse it
Architect: Make sure the project is M.F.B. s to finish the project
3. Life cycle of activity
OnCreate: Called when activity is created, initializes the interface
OnStart: Called when the interface is visible
Onresume: When the button can be clicked
OnPause: When the button loses focus
OnStop: Called when the interface is not visible
OnDestroy: Destroying activity instances
1, when the activity is created, call OnCreate, OnStart, Onresume;
2, when the activity is closed call: OnPause, OnStop, OnDestroy;
3, minimize the activity when called: OnPause, OnStop;
4, the smallest after the call when re-hit: Onrestart, OnStart, Onresume;
4. Startup mode
Singletop: Single top mode set android:launchmode= "Singletop" in the activity's configuration file
If the activity on the stack at the top of the task stack exists, it will not recreate the activity, but instead reuse the existing activity. Ensure that the top of the stack is not created repeatedly if it exists.
Application scenario: Bookmarks for browsers
Singletask: Single task stack, only one instance exists in the current task stack
If there is an instance, empty all other activity on the instance and reuse the instance
Application Scenario: Browser activity
SingleInstance: The startup mode is very special, the activity runs in its own task stack, and only one instance of the task stack exists
If you want to make sure that an activity has only one instance of the entire mobile operating system, use SingleInstance
Application Scenario: Call page Youdao dictionary
Day Seventh:
How to create a broadcast
1. Create a class, inherit the Broadcastreceiver class, and override the OnReceive method
2. Register in the manifest file
<receiver android:name= "package name. Class Name"/>
3. Specify what to filter in the intent filter
<intent-filter >
<action android:name= "Android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
4. Custom Broadcast
1. Create an Intent object that passes the message
Intent Intent = new Intent ();
2. Set the type of event to broadcast
Intent.setaction ("Custom package name");
3. Set the broadcast message data
Intent.putextra ("Key", "Value");
4. Send a broadcast
Sendbroadcast (Intent);
5. Send an orderly broadcast
Intent Intent = new Intent ();
Intent.setaction ("Com.itheima.orderedbroadcast.ZYFFNTBT");
Send an orderly broadcast
Intent Intent
permission specifies that the recipient needs to add permissions
RESULTRECEIVER specifies which broadcast recipient last received a message
Scheduler Message Processor
Initialcode specifying the initial code for the message
Initialdata specifying the data for a message
Initialextras Specifying additional parameters
Sendorderedbroadcast (intent, NULL, NULL, NULL, 1, "Broadcast content:", null);
The configuration file for the broadcast recipient:
<receiver android:name= "Com.itheima.zf.ProvinceBroadCastReceiver" >
<intent-filter android:priority= ">"
<action android:name= "Com.itheima.orderedbroadcast.ZYFFNTBT"/>
</intent-filter>
</receiver>
The code of the broadcast receiver:

String info = Getresultdata ();
SYSTEM.OUT.PRINTLN ("---------Broadcast content:" +info);
Modify broadcast Content
Setresultdata ("State Council began to grant 2014 farmland subsidy: 400 Yuan");
Day Eighth:
1, what is the service
Services under Windows: Applications with no interface, long running in the background
Services under Android: A component of the application, no interface activity, long running in the background
Process: The carrier of the application run
The process is directly related to the application: The Linux operating system creates a process that is responsible for running the Dalvik virtual machine, and the Android application is running on the Dalvik virtual machine.
2. The life cycle of the process
1. When the application starts, it creates a process
2. The process does not exit when the application exits
3, only manually stop the process, the process will end
Understanding: The operating system as long as possible to run the application process, in order to ensure that the memory space is not heavily occupied, it will follow the priority of the process, from low to high level of the killing process, until the memory space is cleaned up until the same time
3, the level of the process
1. Foreground process (foreground processes)
Application, user is working, activity's Onresume method is executed, can respond to click event
2. Visible process (visual processes)
The UI of the application, the user can also see, but cannot manipulate the
3. Service process (services processes)
The application does not have an interface, but a backend service is still in the running state
4. Background process (background processes)
The application is not running, the application is minimized, and the activity executes the OnStop method
5. Empty process (null processes)
No components are running, all activity is closed and the task stack is emptied.
4, the characteristics of the service
Call OnCreate, Onstartcommand when the service is created
The service can only be created once and may be opened multiple times Onstartcommand
Service can only be stopped once
There are no OnPause, OnStop, Onresume, Onrestart methods, because the service has no interface and is running in the background for a long time.
5, Bind mode to open the service life cycle
Bindservice bind service, Unbindservice unbind service
The service is created when it is bound, calls the Onunbind, Ondestrory method, and throws an exception if it is unbound multiple times.
Recommended way:
StartService: Open and create a service, the service is running in the background for a long time;
Bindservice: A binding service that can invoke methods inside the service;
Unbindservice: Relieve the service, stop the service inside the method;
StopService: Stop the service and destroy the service object;
08_ Remote Service Aidl (emphasis)
Local Service: Write the service in the project of your own application, run the service using the process of your own application;
Remote service: A service written in a project of another application that runs the service (an application installed on the same phone) using another application's process;
Ipc:inter Process Communication (interprocess communication);
Aidl:android Interface Definition Language Android interface defined language;
Aidl interface class does not need public, protected, private and other modifiers, the default is publicly shared;
Steps:
1. Create a service interface class containing business logic methods that require external exposure:
2. Let the intermediary in the service realize the Service interface class:
3. Modify and copy the interface file:
4. In the activity of the local Service project, the binding service:
5. Methods for invoking remote services through an interface:
Day Nineth:
1. How to use content providers
Define class inheritance ContentProvider, overriding internal methods as needed
2, configuration under the <application> node of the manifest file, need > in <provider tag

Day:
1. Create a copy of the original in memory
1. Get the original image
Bitmap srcpic = Bitmapfactory.decoderesource (Getresources (), R.DRAWABLE.MEINV);
2. Create a blank paper, reference the original
Bitmap copypic = Bitmap.createbitmap (Srcpic.getwidth (), Srcpic.getheight (), Srcpic.getconfig ());
3. Create an artboard, reference blank paper
Canvas canvas = new canvas (copypic);
4. Create a brush
Paint paint = new paint ();
The default is to use black, followed by the original color painting
Paint.setcolor (Color.Black);
5. Draw on the artboard
Canvas.drawbitmap (Srcpic, matrix,paint);
6. Set the picture for the control
Iv.setimagebitmap (Copypic);

1. Get the resolution of the device screen
WindowManager wm = Getsystemservice (Window_service);
Get device Resolution Object
Display display = Wm.getdefaultdisplay ();
Scale a picture by proportional value
Opts.injustdecodebounds = false;
Opts.insamplesize = scale; 1/scale * 1/scale
Bitmap BM = Bitmapfactory.decodefile (environment.getexternalstoragedirectory () + "/lp.jpg", opts);

Android Core Basic Learning process

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.