StartService play music and stopService

First, there is the MainActivity the
code is as follows:
Here Insert Picture DescriptionPackage com.example.jiyeliaoyuan.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;
//Service
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_startService,btn_stopService,clear_tv_1;
private Intent intent;
public static TextView tv_1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn_startService=(Button)findViewById(R.id.btn_start);
    btn_stopService=(Button)findViewById(R.id.btn_stop);
    tv_1=(TextView)findViewById(R.id.tv_1);
    clear_tv_1=(Button)findViewById(R.id.clear_tv_1);
    btn_startService.setOnClickListener(this);
    btn_stopService.setOnClickListener(this);
    clear_tv_1.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btn_start:
            intent=new Intent(getApplicationContext(),MyService.class);
            startService(intent);
            break;
        case R.id.btn_stop:
            stopService(intent);
            break;
        case R.id.clear_tv_1:
            tv_1.setText("显示:");
            break;
    }
}

}
Second, MyService class inheritance make-Service
// lifecycle
public class-Service {MyService the extends
@Nullable
the MediaPlayer mediaPlayer;
public onBind the IBinder (the Intent Intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    MainActivity.tv_1.setText(MainActivity.tv_1.getText()+"onstart--------2"+"\n																			");
     mediaPlayer.start();
    return super.onStartCommand(intent, flags, startId);
    
}

@Override
public void onCreate() {
    super.onCreate();
    MainActivity.tv_1.setText(MainActivity.tv_1.getText()+"\n"+"onCreate--------1"+"\n");
    mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.a);
}

@Override
public void onDestroy() {
    super.onDestroy();
    MainActivity.tv_1.setText(MainActivity.tv_1.getText().toString()+"onDestroy--------3"+"\n");
        mediaPlayer.stop();


}

}
// Register Service Mainifests in the
code as follows:

Published 18 original articles · won praise 3 · Views 1048

Guess you like

Origin blog.csdn.net/qq_45393395/article/details/100546229