Android Four component Learning summary and individual component examples (1)

Source: Internet
Author: User

Android Four components are activity, service, content provider, broadcast receiver, respectively. First, Android four components of the detailed 1. Activity(1) an activity is usually a separate screen (window). (2) communication between activity through intent. (3) every activity in an Android app must be declared in the Androidmanifest.xml configuration file, or the activity will not be recognized or executed by the system. (4) Activity life cycle
> What is the life cycle?
The methods that must be executed from the time the object is created to the stage of the destruction, which are the callbacks for the life cycle
The 7 methods and functions of activity:
* OnCreate () method to invoke when activity is created
> Initialization of UI Interface Setcontentview ()
* OnDestroy () method to invoke when activity is destroyed
> Interface exit before the wrap up operation, SMS sender, before exiting the data save.
* OnStart () activity interface user visible
> Update UI action, play video
* ONSTOP () Activity interface user is no longer visible
> screen is not visible, pause video playback
* Onresume ()
> Interface gets focus, button can click event
* OnPause ()
> The interface loses focus, the button can not click the event accordingly
* Onrestart ()
>activity is minimized, and is not destroyed, if you open the activity again next time.
> Re-user interface visible
Life cycle of activity:
# # #完整生命周期 (entire lifetime)
Oncreate-->onstart-->onresume-->onpause-->onstop-->ondestory
# # #可视生命周期 (Visible lifetime)
Onstart-->onresume-->onpause-->onstop
# # #前台生命周期 (foreground lifetime)
Onresume-->onpause take an example of seven ways to implement activity with a small game:1. First set up a project engineering document: This project to achieve three functions: the demonstration of the Activty seven methods, transparent background, locking screen;2. First configure the page layout file as follows:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android "Xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "android:layout_height=" match _parent "android:orientation=" vertical "> <textview android:layout_width=" wrap_content "Android:layo        ut_height= "Wrap_content" android:text= "I am the main interface"/> <button android:layout_width= "Match_parent"    android:layout_height= "Wrap_content" android:text= "Start second Interface" android:onclick= "click"/> <button android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "Play Strange "android:onclick=" Click1 "/> <textview android:id=" @+id/tv "android:layout_width=" WR Ap_content "android:layout_height=" wrap_content "android:text="/></LINEARLAYOUT> 

3. Then configure Mainactivity.java

Package Com.xunfang.activity;import Android.app.activity;import Android.content.intent;import android.os.Bundle; Import Android.view.view;import Android.widget.textview;public class Mainactivity extends Activity {private TextView TV ;p rivate int blood = 100; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); SYSTEM.OUT.PRINTLN ("interface created");//finish ();//Get the monster's blood trough TV = (TextView) Findviewbyid (r.id.tv);} @Overrideprotected void OnStart () {Super.onstart (); SYSTEM.OUT.PRINTLN ("interface can be seen");} @Overrideprotected void Onresume () {super.onresume (); System.out.println ("I Got the Spotlight");} @Overrideprotected void Onrestart () {Super.onrestart (); SYSTEM.OUT.PRINTLN ("User restart Interface");} @Overrideprotected void OnPause () {super.onpause (); System.out.println ("I lost Focus");} @Overrideprotected void OnStop () {super.onstop (); SYSTEM.OUT.PRINTLN ("The interface is not visible");} @Overrideprotected void OnDestroy () {Super.ondestroy (); SYSTEM.OUT.PRINTLN ("The interface has been destroyed");} public void Click (ViEW view) {Intent Intent = new Intent (this,secondactivity.class); startactivity (Intent);} public void Click1 (view view) {//per click, let the Monster's blood Fall Love 6 points blood-= 6;//Set the blood back to the monster Tv.settext (Blood + ");}

3. Configure Androidmanifest.xml, which let the system's environment is not in the Go sensitive screen switch, the code is android:configchanges= "Orientation|screensize|keyboardhidden" The transparent interface code is as follows: Android:theme= "@android: Style/theme.translucent", if you want to set the APK icon, it is necessary to call the settings, I call the System icon: android:icon= "@ Android:drawable/arrow_up_float "Specific code is as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.xunfang.activity "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion=" "/> <application android:allowbackup=" True "android:icon=" @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/app Theme "> <activity android:name=". Mainactivity "android:icon=" @android:d rawable/arrow_up_float "android:label=" I am the main interface "Android            Oid:configchanges= "Orientation|keyboardhidden|screensize" Android:theme= "@android: Style/theme.translucent"            > <!--transparent interface translucent: Transparent android:theme= "@android: Style/theme.translucent" -<intent-filter> <action android:name= "android.intent.action. MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-filte r> </activity> <activity android:name= "com.xunfang.activity.SecondActivity" > </act Ivity> </application></manifest>

4.second.xml and Secondactivity.java are all system default generated, do not have to change, and then you can directly test to see how the effect.

2.content provider

The Android platform provides content provider to make the specified data set for an application available to other applications. This data can be stored in a file system, in a SQLite database, or in any other reasonable way,

Overall idea:

# #对文件的内容提供者
1. There is an application that takes a private file, and the requirement is to expose this private file.
2. Write a subclass of ContentProvider
3. Define matching rules
* Define the Urimatcher of the matching device
* Define matching rules Murimatcher.adduri ("com.xunfang.content", "filename", SUCCESS);
4. Overriding the OpenFile method
5. Declaring the Content provider section in the manifest file
<provider
Android:name= "Com.xunfang.provider.DBProvider"
Android:authorities= "Com.xunfang.sql"
></provider>

Here's an example of saving data:

1. Create a new project as shown in

2. Configure the Mainactivity.java as follows:

Package Com.xunfang.openfile;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Android.app.activity;import Android.content.context;import Android.os.bundle;import Android.view.Menu;import Android.view.menuitem;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.toast;public class MainActivity extends    Activity {private EditText name;private Button save;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Initview ();    Setlister (); }private void Initview () {name = (EditText) Findviewbyid (r.id.et_name); save = (Button) Findviewbyid (r.id.btn_save);} private void Setlister () {Save.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {String uname = Name.gettext (). toString (). Trim (); String path = Getfilesdir () + "/private.txt"; try{FileOutputStream fos = new FileOutputStream (path); Fos.write (Uname.getbytes ()); Fos.close (); Toast.maketext (Getapplicationcontext (), "Save succeeded", 0). Show (); catch (Exception e) {e.printstacktrace ();}}});}}

The

 fileprovider.java is configured as follows:

Package Com.xunfang.fileprovider;import Java.io.file;import Java.io.filenotfoundexception;import Android.content.contentprovider;import Android.content.contentvalues;import Android.content.urimatcher;import Android.database.cursor;import Android.net.uri;import Android.os.parcelfiledescriptor;public class FileProvider Extends ContentProvider {private static final urimatcher Matcher = new Urimatcher (urimatcher.no_match);p rivate static fin Al int SUCCESS = 1;static{matcher.adduri ("Com.xunfang.openfile", "Private.txt", SUCCESS);} @Overridepublic Boolean onCreate () {return false;} @Overridepublic Cursor query (Uri uri, string[] projection, string selection,string[] Selectionargs, string sortOrder) {RE Turn null;} @Overridepublic String getType (Uri uri) {return null;} @Overridepublic uri insert (URI uri, contentvalues values) {return null;} @Overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {return 0;} @Overridepublic int update (URI uri, contentvalues values, String selectioN,string[] Selectionargs) {return 0;} @Overridepublic parcelfiledescriptor openFile (URI Uri, String mode) throws FileNotFoundException {if (Matcher.match (URI ) = = SUCCESS) {File File = new file (GetContext (). Getfilesdir (), Uri.getpath ()); return Parcelfiledescriptor.open (file, parcelfiledescriptor.mode_read_only);} Else{return super.openfile (URI, mode);}}}

Finally, in the Androidmainfest.xml

You can do it.

Service, broadcast receiver two components will be carefully explained in the next blog post!

Android Four component Learning summary and individual component examples (1)

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.