简体   繁体   English

音频文件在Android每次启动活动时都播放了多次?

[英]Audio file played multiple times on starting activity each time in android?

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 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; 服务代码:包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;
   }

   }

Add this peace of code in your MainActivity,hope it helps, 在您的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));
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM