Android中Service服务详解(一)

2019-12-10 19:19:36丽君

3、布局文件activity_main.xml

<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
  <Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="启动服务" />
  <Button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="停止服务" />
</LinearLayout>

4、MainActivity.java文件

package com.example.testservice;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
  private Button startService_Button;
  private Button stopService_Button;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //获取开启服务按钮
    startService_Button = (Button) findViewById(R.id.button1);
    //获取停止服务按钮
    stopService_Button = (Button) findViewById(R.id.button2);
    //调用点击事件
    startService_Button.setOnClickListener(this);
    stopService_Button.setOnClickListener(this);
  }
  /**
   * 点击事件
   */
  @Override
  public void onClick(View view) {
    switch(view.getId()){
    case R.id.button1:
      //"开启服务"按钮
      Intent startIntent = new Intent(this,MyService.class);
      //开启服务
      startService(startIntent);
      break;
    case R.id.button2:
      //"停止服务"按钮
      Intent stopIntent = new Intent(this,MyService.class);
      //停止服务
      stopService(stopIntent);
      break;
    default:
      break;
    }
  }
  @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;
  }
}

三、测试结果

发布项目后,如下所示:

Android中Service服务详解(一)