码迷,mamicode.com
首页 > 移动开发 > 详细

Android中Service通信(一)——启动Service并传递数据

时间:2016-12-22 11:53:53      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:bsp   cti   ros   ons   print   etc   read   ext.get   sys   

启动Service并传递数据的小实例(通过外界与服务进行通信):

1、activity_main.xml:

  <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="默认信息"
    android:id="@+id/etData"/>

  <Button
    android:text="启动服务"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btnStartService" />

  <Button
    android:text="停止服务"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btnStopService" />

2、MainActivity.java:

  public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      editText = (EditText) findViewById(R.id.etData);
      findViewById(R.id.btnStartService).setOnClickListener(this);
      findViewById(R.id.btnStopService).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
      Intent i = new Intent(this,MyService.class);
      switch(v.getId()){
        case R.id.btnStartService:
          i.putExtra("data",editText.getText().toString());   //获取默认信息
          startService(i);
        break;
        case R.id.btnStopService:
          stopService(i);
        break;
      }
    }
  }

3、MyService.java:

  public class MyService extends Service {

    private boolean running = false;
    private String data = "这是默认信息";

    public MyService() {}

    @Override
    public IBinder onBind(Intent intent) {
      // TODO: Return the communication channel to the service.
      throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
      data = intent.getStringExtra("data");   //获取Intent里面的数据
      return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
      super.onCreate();

      running = true;
      new Thread(){
        @Override
        public void run() {
          super.run();
          while(running){
            System.out.println(data);
            try {
              sleep(1000);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
            }
         }
       }.start();
    }

    @Override
    public void onDestroy() {
      super.onDestroy();
      running = false;
    }
  }

 

Android中Service通信(一)——启动Service并传递数据

标签:bsp   cti   ros   ons   print   etc   read   ext.get   sys   

原文地址:http://www.cnblogs.com/MRDS-world/p/6210048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!