Android -- 啟動Service並傳遞資料

來源:互聯網
上載者:User

標籤:android

繼上一篇文章:http://blog.csdn.net/gaopeng0071/article/details/45153495

本文主要記錄Activity傳遞資料到Service。
源碼與上一篇基本是保持一致的,只是在跳轉過程中增加了參數的傳遞。

我們先來看效果。
1、


2、通過以上,可以看出activity頁面的數值改變,相應後台service輸出的數值也跟著改變。
3、核心代碼如下,看代碼中的38行,我們使用之前學過的只是,使用Intent作為載體,裝載activity頁面上的資料。

package com.example.connectservice;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.EditText;public class MainActivity extends Activity implements OnClickListener {    private EditText 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()) {        case R.id.startService:            Intent i = new Intent(this, MyService.class);            i.putExtra("data", edit.getText().toString());            startService(i);            break;        case R.id.stopService:            stopService(new Intent(this, MyService.class));            break;        }    }}

4、Service代碼如下,詳見代碼的21行,我們在onStartCommand方法中通過intent參數擷取activity傳過來的值。

package com.example.connectservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.widget.EditText;public class MyService extends Service {    String data;    boolean running = false;    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        return null;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        data = intent.getStringExtra("data");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onCreate() {        super.onCreate();        running = true;        new Thread() {            public void run() {                while (running) {                    System.out.println("Service中擷取到的資料:" + data);                    try {                        Thread.sleep(1000);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                }            };        }.start();    }    @Override    public void onDestroy() {        super.onDestroy();        running = false;    }}

其他代碼

<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" >    <EditText        android:id="@+id/editText1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:ems="10" >        <requestFocus />    </EditText>    <Button        android:id="@+id/startService"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="startService" />    <Button        android: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-sdk        android:minSdkVersion="8"        android:targetSdkVersion="21" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android: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>        <service             android:name=".MyService"            android:enabled="true"            android:exported="true">        </service>    </application></manifest>

Android -- 啟動Service並傳遞資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.