编写一个MainActivity和MyService,在MainActivity中的onCreate()函数中为两个按钮分别设置点击事件监听器,点击第一个按钮启动服务弹出一个Toast显示“您点击了第一个按钮”,点击第二个按钮启动服务弹出一个Toast显示“您点击了第二个按钮”。(以action区分不同的动作)

  • MainActivity.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Button button1 = findViewById(R.id.button1);
    Button button2 = findViewById(R.id.button2);
    button1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent intent = new Intent(MainActivity.this, MyService.class);
    intent.setAction("ACTION_BUTTON_1");
    startService(intent);
    }
    });
    button2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent intent = new Intent(MainActivity.this, MyService.class);
    intent.setAction("ACTION_BUTTON_2");
    startService(intent);
    }
    });
    }
    }
  • MyService.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    String intentAction = intent.getAction();
    if (intentAction.equals("ACTION_BUTTON_1")) {
    Toast.makeText(this, "您点击了第一个按钮", Toast.LENGTH_LONG).show();
    } else if (intentAction.equals("ACTION_BUTTON_2")) {
    Toast.makeText(this, "您点击了第二个按钮", Toast.LENGTH_LONG).show();
    }
    return super.onStartCommand(intent, flags, startId);
    }
    }