Android -- start the Service and pass data
Following the previous article: http://blog.csdn.net/gaopeng0071/article/details/45153495
This document records the data transmitted by the Activity to the Service.
The source code is basically consistent with the previous article, but the parameter transfer is added during the jump process.
Let's first look at the effect.
1,
2. From the above, we can see that the value of the activity page has changed, and the value of the corresponding background service output has also changed.
3. The core code is as follows. Check 38 lines in the Code. All we have learned before is to use Intent as the carrier to load data on the activity page.
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. The Service Code is as follows. For details, see line 21 of the Code. We can use the intent parameter in the onStartCommand method to obtain the value passed by the 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 (data obtained in 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 ;}}