============================================================================================
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp" > <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center" android:text="歌曲名称:" android:textColor="@color/black" android:textSize="17sp" /> <EditText android:id="@+id/et_song" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:layout_margin="5dp" android:background="@drawable/editext_selector" android:hint="请填写歌曲名称" android:textColor="@color/black" android:textSize="17sp" /> </LinearLayout> <Button android:id="@+id/btn_send_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="开始播放音乐" android:textColor="#000000" android:textSize="17sp" /> </LinearLayout>
代码:
package com.example.myapplication; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity6 extends AppCompatActivity implements View.OnClickListener { private EditText et_song; private Button btn_send_service; private boolean isPlaying = true; // 是否正在播放 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main6); et_song = findViewById(R.id.et_song); btn_send_service = findViewById(R.id.btn_send_service); btn_send_service.setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.btn_send_service) { if (TextUtils.isEmpty(et_song.getText())) { Toast.makeText(this, "请填写歌曲名称", Toast.LENGTH_SHORT).show(); return; } // 创建一个通往音乐服务的意图 Intent intent = new Intent(this, MusicService.class); intent.putExtra("is_play", isPlaying); // 是否正在播放音乐 intent.putExtra("song", et_song.getText().toString()); btn_send_service.setText(isPlaying?"暂停播放音乐":"开始播放音乐"); startService(intent); // 启动音乐播放服务 isPlaying = !isPlaying; } } }
MusicService
====================================================================================================
原创文章,作者:jamestackk,如若转载,请注明出处:https://blog.ytso.com/tech/276704.html