Examples of Service usage developed by Android

  • 2020-06-19 11:43:28
  • OfStack

An example of Service is presented in this paper. Share to everybody for everybody reference. The specific analysis is as follows:

Service is a program with a long life cycle and no interface.

Here's an example that plays mp3.

Look at the MainActivity java


package com.example.servicetest; 
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 { 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Button btnstart = (Button) findViewById(R.id.btnstart); 
    btnstart.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        startService(new Intent("com.yarin.Android.MUSIC")); 
      } 
    }); 
    Button btnstop = (Button) findViewById(R.id.btnstop); 
    btnstop.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        stopService(new Intent("com.yarin.Android.MUSIC")); 
      } 
    }); 
  } 
}

Two buttons are defined on the interface.

Then look at MusicService java


package com.example.servicetest; 
import android.app.Service; 
import android.content.Intent; 
import android.media.MediaPlayer; 
import android.os.IBinder; 
public class MusicService extends Service { 
  private MediaPlayer player; 
  @Override 
  public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
  } 
  public void onStart(Intent intent, int startId) { 
    super.onStart(intent, startId); 
    player = MediaPlayer.create(this, R.raw.a); 
    player.start(); 
  } 
  public void onDestroy() { 
    super.onDestroy(); 
    player.stop(); 
  } 
}

Defines what to do with start and destroy.

Create a new raw folder in the res directory and place a.mp3 in that directory.

That way, when you click the Start button, you can play that mp3 file. Click Stop to stop the play.

Hopefully, this article has helped you with your Android programming.


Related articles: