本实例演示启动Service,并通过从Activity向Service传递数据,新建一个Service,并敲如下代码:
package com.example.lhb.startservice;import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.view.ViewDebug;
import android.widget.Toast;public class MyService extends Service {private boolean Running=false;private String data="默认信息!!!";public MyService() {}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) { data=intent.getStringExtra("data");//这里的intent是参数里的,不是自定义的return super.onStartCommand(intent, flags, startId);}@Overridepublic void onCreate() {super.onCreate();Running=true;new Thread(){@Overridepublic void run() {super.run();while (Running){System.out.println(data);try {sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}}}.start();}@Overridepublic void onDestroy() {super.onDestroy();Running=false;}
}
主程序代码:
package com.example.lhb.startservice;import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;public class MainActivity extends ActionBarActivity {private EditText inputText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.btnStartService).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {inputText= (EditText) findViewById(R.id.inputText);if(inputText.getText().length()==0){Toast.makeText(MainActivity.this,"请输入传递的值!",Toast.LENGTH_SHORT).show();return;}Intent intent;intent=new Intent(MainActivity.this,MyService.class);intent.putExtra("data",inputText.getText().toString());startService(intent);}});findViewById(R.id.btnStopService).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent;intent=new Intent(MainActivity.this,MyService.class);stopService(intent);}});}
}