0

I am trying to create an app with background music. My app uses two activities and one service(to play the music in background). I am now stuck as as soon as I go back to the original activity the whole procedure is repeated and two instances of the song are played together. This problem multiplies further. Please help. A newbie in android :P

Source Code of main activity:

package com.example.app;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
MediaPlayer mediaPlayer;
public final static String EXTRA_MESSAGE="com.example.app.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //the service just plays the a.mp3 in res/raw
    startService(new Intent(getBaseContext(), Music.class));
}

@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;
}

public void sendMessage(View view){
    //this activity just displays the entered text
    Intent intent=new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message=editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

}

the Service code: package com.example.app;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

 public class Music extends Service {

@Override
   public IBinder onBind(Intent arg0) {
      return null;
}

    @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
  MediaPlayer mediaPlayer=MediaPlayer.create(this,R.raw.a);
  if(!mediaPlayer.isPlaying())
  {
       mediaPlayer.start();
  }
  return START_STICKY;
   }

   }
4

1 回答 1

1

在您的 MainActivity 中添加此代码和平,希望它有所帮助,

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// this line let's the service start only once.
if(savedInstanceState==null)
{
startService(new Intent(getBaseContext(), Music.class));
}
}
于 2013-06-07T14:24:26.560 回答