Android-Start service and pass data

Source: Internet
Author: User

Following previous article: http://blog.csdn.net/gaopeng0071/article/details/45153495

This article primarily records activity delivery data to the service.
The source code and the previous article is basically consistent, but in the jump process to increase the transfer of parameters.

Let's look at the effect first.
1.


2, through the above, you can see the activity page value changes, the corresponding background service output value also changed.
3, the core code is as follows, look at the code of 38 lines, we used to learn only, using intent as a carrier, loading the activity page data.

 PackageCom.example.connectservice;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.content.Intent;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.EditText; Public  class mainactivity extends Activity implements Onclicklistener  {    PrivateEditText edit;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Findviewbyid (R.id.startservice). Setonclicklistener ( This); Findviewbyid (R.id.stopservice). Setonclicklistener ( This);    Edit = (EditText) Findviewbyid (R.ID.EDITTEXT1); }@Override     Public Boolean Oncreateoptionsmenu(Menu menu) {//inflate the menu; This adds items to the action bar if it is present.Getmenuinflater (). Inflate (R.menu.main, menu);return true; }@Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.startservice:intent i =NewIntent ( This, Myservice.class); I.putextra ("Data", Edit.gettext (). toString ()); StartService (i); Break; CaseR.id.stopservice:stopservice (NewIntent ( This, Myservice.class)); Break; }    }}

4, the service code is as follows, see the Code of 21 lines, we in the Onstartcommand method through the intent parameter to get the value of activity passed over.

 PackageCom.example.connectservice;ImportAndroid.app.Service;ImportAndroid.content.Intent;ImportAndroid.os.IBinder;ImportAndroid.widget.EditText; Public  class myservice extends Service {String data;Booleanrunning =false;@Override     PublicIBinderOnbind(Intent Intent) {//TODO auto-generated method stub        return NULL; }@Override     Public int Onstartcommand(Intent Intent,intFlagsintStartid) {data = Intent.getstringextra ("Data");return Super. Onstartcommand (Intent, flags, Startid); }@Override     Public void onCreate() {Super. OnCreate (); running =true;NewThread () { Public void Run() { while(running) {System.out.println ("Data obtained in service:"+ data);Try{Thread.Sleep ( +); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace ();        }                }            };    }.start (); }@Override     Public void OnDestroy() {Super. OnDestroy (); running =false; }}

Other code

<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:paddingbottom="@dimen/activity_vertical_margin"    Android:paddingleft="@dimen/activity_horizontal_margin"    Android:paddingright="@dimen/activity_horizontal_margin"    Android:paddingtop="@dimen/activity_vertical_margin"    android:orientation="Vertical"    Tools:context=". Mainactivity ">    <EditTextandroid:id="@+id/edittext1"android:layout_width="Match _parent "android:layout_height=" Wrap_content "android:ems=" Ten " >                                         <requestfocus />    </EditText>    <button  android:id  = "@+id/startservice"  android:layout_width
      = "wrap_content"  android:layout_height  =         "wrap_content"  android:text  = "StartService" />     <buttonandroid:id="@+id/stopservice"android:layout_width="Wrap_ Content "android:layout_height="wrap_content "android:text=" StopService " />                                </linearlayout>
<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android"  package ="Com.example.connectservice"android:versioncode="1"android: Versionname="1.0" >                <uses-sdkandroid:minsdkversion="8"android:targetsdkversion ="/>"                     <applicationandroid:allowbackup="true"android:icon="@drawable/ Ic_launcher "android:label=" @string/app_name "android:theme=" @style/apptheme " >                                        <activityandroid:name=". Mainactivity "android:label=" @string/app_name " >                                    <intent-filter>                <action android:name="Android.intent.action.MAIN" />                <category android:name="Android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <serviceandroid:name=". MyService "android:enabled=" true "android:exported=" true ">                                              </Service>    </Application></manifest>

Android-Start service and pass data

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.