Android (Xamarin) Tour (Fri)

Source: Internet
Author: User

Original: Android (Xamarin) Tour (Fri)

January 23, 2016, Beijing ushered in a very painful day, frozen baby, a day did not out of my own little black house, in this room to entertain themselves. I don't know about you.

For Android's four basic components (Activity, Service, broadcast Receiver, Content Provider),

We have described the activity, the most basic activities of the Unit, any one of the activities of the processing, all need him, the previous introduction of the dialog box, layout, prompt message, basic content settings and so on. Broadcase Receiver, broadcast, is mainly used to asynchronously accept intent (messenger), in four when there is a small example, today we say the Service.

First, Service

   Service can be used in multi-occasions applications, such as multimedia playback when the user started other activity this time the program to continue to play in the background, such as the detection of changes in the file on the SD card, or in the background to record your geographic information changes and so on, in short service , always hidden behind. The service is run in the background for an indefinite period of time and does not interact with the user application component. Each service must be declared by <service> in manifest. Can be started by Contect.startservice and Contect.bindserverice.

Among the methods involved are:

    OnCreate: will only be called when the service is first opened, mainly responsible for some of the initialization code.

    Onstartcommand: This method is called every time the service is started, possibly from StartService or by a system restart. It is generally responsible for opening tasks that take a long time. The method also returns an enumeration of type Startcommandresult that will affect the details of the system restarting the service.

    OnDestroy: Called when the service uses Stopself or StopService, primarily to release resources, and so on.

One thing to note is that when we write in Java, we need to add a service in Androidmanifest.xml , but in Xamarin, we don't need to be so complicated, we just add a description [service] to the beginning. you can do it. In fact, it's like a simple filter. Where the filter is already mentioned in the preceding implicit intent.

    [Service]    public class Mainservice:service    {    }

Create a new project, and then add a class to the project, directly under the root directory to Mainservice, then inherit the serviceand implement it.

The first thing to do is to implement the Onbind method, which is necessary, so we can return null directly.

     public override IBinder Onbind (Intent Intent)        {            return null;        }

Then talk about the method involved:OnCreate, here are all three methods are rewritten, because, in Android, most of the methods are provided, so, in general, we need to do is to implement a variety of interfaces. Then all kinds of inheritance can be. Add the following method to the added class.

        public override void OnCreate ()        {            base. OnCreate ();            Log.debug ("Xamarin", "oncreate_create");        }

Onstartcommand, say a simple trick in the IDE (vs the world's most powerful IDE, no one, haha) directly override the method name, and then press the table key directly once. Automatic completion of the OH.

        public override Startcommandresult Onstartcommand (Android.Content.Intent Intent, startcommandflags flags, int startid)        {            log.debug ("Xamarin", "Onstartcommand_start");            return startcommandresult.sticky;        }

OnDestroy (), again, we can see it directly in Debug.

        public override void OnDestroy ()        {            base. OnDestroy ();            Log.debug ("Xamarin", "ondestroy_stop");        }

OK, the full service code has been set up and completed. As follows

using system;using system.collections.generic;using System.Linq;using System.text;using android.app;using android.content;using android.os;using android.runtime;using Android.Views;         Using android.widget;using android.util;namespace test022_service{[Service] public class Mainservice:service { public override void OnCreate () {base.            OnCreate ();        Log.debug ("Xamarin", "oncreate_create"); } public override Startcommandresult Onstartcommand (Android.Content.Intent Intent, startcommandflags flags, int STA            Rtid) {log.debug ("Xamarin", "Onstartcommand_start");        return startcommandresult.sticky; } public override void OnDestroy () {base.            OnDestroy ();        Log.debug ("Xamarin", "ondestroy_stop");        } public override IBinder Onbind (Intent Intent) {return null; }    }}

Next, we'll add the interface code and add a button to start the service and stop the service in Main.axml. (Button)

<?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 ">    <button        android:id=" @+id/startservice "        android:layout_width=" Fill_parent        " android:layout_height= "Wrap_content"        android:text= "start service"/>    <button        android:id= "@+id/ StopService "        android:layout_width=" fill_parent "        android:layout_height=" Wrap_content "        android: text= "Stop Service"/></linearlayout>

Corresponding backstage, direct start can, in the previous article mentioned StartActivity, but here is the start service, so the use of StartService can, similarly, stop service, is also StopService.

        protected override void OnCreate (bundle bundle)        {            base. OnCreate (bundle);            Setcontentview (Resource.Layout.Main);            Button start = findviewbyid<button> (Resource.Id.startService);            Start. Click + = Start_click;            Button stop = findviewbyid<button> (Resource.Id.stopService);            Stop. Click + = Stop_click;        }        private void Stop_click (object sender, EventArgs e)        {            Toast.maketext (this, "Stop service", Toastlength.short). Show ();            StartService (New Intent (This, typeof (Mainservice)));        }        private void Start_click (object sender, EventArgs e)        {            Toast.maketext (this, "Start service", Toastlength.short). Show ();            StopService (New Intent (This, typeof (Mainservice)));        }

Here, our service has been completed. Start the project and view it in the virtual machine.

, how to check when the service starts successfully, there is only one hint message, let's look at the IDE.

Click on our Output window here.

Is it possible to see the code written in the service log.debug ().

So how do we know if that service starts up, then let's change the code to

Onstartcommand (Android.Content.Intent Intent, startcommandflags flags, int startid)

  public override Startcommandresult Onstartcommand (Android.Content.Intent Intent, startcommandflags flags, int startid)        {            log.debug ("Xamarin", "Onstartcommand_start");            New Thread (() =            {                log.debug ("Xamarin", Startid + "service thread Start");                Thread.Sleep (+);                Log.debug ("Xamarin", Startid + "service thread Off");                Stopself (Startid);            }). Start ();            return startcommandresult.sticky;        }

Then, there are classmates asked, the thread in the end is to use Java.lang or system.threading it, in fact, here is no difference, because all is to start a thread .

OK, run, see if the Output window is visible.

Second, the Android data storage

In Android, the SQLite database is available, which is a lightweight embedded database engine that supports the SQL language and has good performance with very little memory. Today's mainstream mobile devices like Android, iphone and so on are using SQLite as a storage engine for complex data, when we develop applications for mobile devices, we may have to use SQLite to store our large amount of data, So we need to master the SQLite development skills on mobile devices, the Sqlitedatabase class provides us with many ways to add, update and delete, we can use.

Let's do a test. First, add a new project.

First, add a button to the page to create and add data, and so on. and add a ListView to display the data we just added.

<?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 ">    <button        android:id=" @+id/mybutton "        android:layout_width=" Fill_parent        " android:layout_height= "Wrap_content"        android:text= "click to start adding Data"/>    <listview        android:minwidth= " 25px "        android:minheight=" 25px "        android:layout_width=" match_parent "        android:layout_height=" match _parent "        android:id=" @+id/listview1 "/></linearlayout>

The background then creates a Arrayadapter (data adapter) to accept the data and display it on the page.

In this case, if we want to throw an exception, it is best to use the Android sqlitedatabasecorruptexception, do not use exception, this is not catch the exception .

Using system;using android.app;using android.content;using android.runtime;using android.views;using Android.Widget; Using android.os;using android.database.sqlite;using android.database;namespace test018{[Activity (Label = "Add Database", Ma Inlauncher = true, Icon = "@drawable/myapk")] public class Mainactivity:activity {protected override void OnCreate (Bundle bundle) {base.            OnCreate (bundle);            Set our view from the "main" layout resource Setcontentview (Resource.Layout.Main); Get our buttons from the layout resource,//and attach a event to it button button = findviewbyi            D<button> (Resource.Id.MyButton); button.                Click + = delegate {var list = findviewbyid<listview> (Resource.Id.listView1); List.            Adapter = Createlocaldb ();        }; } private arrayadapter<string> Createlocaldb () {Findviewbyid<buTton> (Resource.Id.MyButton).            SetText (RESOURCE.STRING.INSERTDB);            arrayadapter<string> adapter = new Arrayadapter<string> (this, Android.Resource.Layout.SimpleListItem1);            string file = "";                try {Random rand = new Random (); The path//using (sqlitedatabase db = this) when the database was created. Openorcreatedatabase ("1.db", filecreationmode.private, NULL)) {db.                    Execsql ("CREATE table IF not EXISTS t_person (ID integer PRIMARY key autoincrement,age integer,name text)"); for (int i = 0; i < 5; i++) {var item = rand.                        Next (10, 99); Db.                    Execsql ("INSERT into T_person (age,name) VALUES (?,?)", new java.lang.object[] {item, "Jeff" + item}); } using (ICursor cursor = db. Rawquery ("SELECT * from T_person", null)) {                       ADO.Net.reader.Read () reads the data while (cursor. MoveToNext ()) {int id = cursor. GETINT (cursor.                            Getcolumnindex ("ID")); int age = cursor. GETINT (cursor.                            Getcolumnindex ("Age")); String name = cursor. GetString (cursor.                            Getcolumnindex ("Name")); Adapter.                        ADD (id + ": I am" + name + ", I am this year" + age);                    }}///Get to the current database path// File = this. Getdatabasepath ("1.db").                Path; }}////sqlitedatabasecorruptexception Throw database exception//catch (Sqlitedat                Abasecorruptexception e) {e.tostring (); Adapter. Add ("added failed!            "); } adapter.            ADD (file);        return adapter; }    }}

, you can get to know them according to some of the comments. Let's run it and look at the effect. To find the path of the classmate note the last sentence,file = this. Getdatabasepath ("1.db"). Path; This program has been tested on my own Android phone, completely feasible, haha. Look at the virtual machine effect. Click the button directly.

is not feeling very handsome appearance, in fact, I think so.

See this article of the sister paper, kanji, point your cute little hand, to recommend, younger brother this Chamber has a ceremony.

  

Android (Xamarin) Tour (Fri)

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.