-
1、效果图

2、通过以上效果图,可以看出activity页面的数值改变,相应后台service输出的数值也跟着改变。
3、核心代码如下,看代码中的38行,使用Intent作为载体,装载activity页面上的数据。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748<codeclass="hljs"java="">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;publicclassMainActivityextendsActivityimplementsOnClickListener {privateEditText edit;@OverrideprotectedvoidonCreate(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);}@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);returntrue;}@OverridepublicvoidonClick(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;}}}</code>4、Service代码如下,详见代码的21行,我们在onStartCommand方法中通过intent参数获取activity传过来的值。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152<codeclass="hljs"java="">packagecom.example.connectservice;importandroid.app.Service;importandroid.content.Intent;importandroid.os.IBinder;importandroid.widget.EditText;publicclassMyServiceextendsService {String data;booleanrunning =false;@OverridepublicIBinder onBind(Intent intent) {// TODO Auto-generated method stubreturnnull;}@OverridepublicintonStartCommand(Intent intent,intflags,intstartId) {data = intent.getStringExtra(data);returnsuper.onStartCommand(intent, flags, startId);}@OverridepublicvoidonCreate() {super.onCreate();running =true;newThread() {publicvoidrun() {while(running) {System.out.println(Service中获取到的数据: + data);try{Thread.sleep(1000);}catch(InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};}.start();}@OverridepublicvoidonDestroy() {super.onDestroy();running =false;}}</code>12345678910111213141516<codeclass="hljs"xml=""><manifest android:versioncode="1"android:versionname="1.0"package="com.example.connectservice"xmlns:android="http://schemas.android.com/apk/res/android"><uses-sdk android:minsdkversion="8"android:targetsdkversion="21"><intent-filter><category android:name="android.intent.category.LAUNCHER"></category></action></intent-filter></activity><service android:enabled="true"android:exported="true"android:name=".MyService"></service></application></uses-sdk></manifest></code>
