无法将数据从“活动”传递到“服务”

时间:2015-04-01 09:51:03

标签: android

首先,我按照本教程制作了音乐播放器应用程序。 http://www.java2s.com/Code/Android/Media/UsingServicetoplaymediafile.htm

该应用程序正常。之后我修改了代码,以便从MainActivity发送一个到Service的链接,以便服务中的MediaPlayer可以从链接中流式传输音频。现在应用程序无法运行。当我点击"开始播放"按钮应用程序崩溃。我在Manifest文件中添加了Internet权限。以下是我的代码。

MainActivity.java

package com.example.musicplayer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity implements OnClickListener {

      Button startPlaybackButton, stopPlaybackButton;
      Intent playbackServiceIntent;

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

        startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
        stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);

        startPlaybackButton.setOnClickListener(this);
        stopPlaybackButton.setOnClickListener(this);

        playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
      }

      public void onClick(View v) {
        if (v == startPlaybackButton) {

          playbackServiceIntent.putExtra("song_link", "http://a2z3gp.com/Telugump3%20Songs/Telugump3/A%20TO%20Z%20TELUGU%20HQ%20MP3%20SONGS/E/Eduruleni%20Manishi/Are_Eelakotti.mp3" );
          startService(playbackServiceIntent);

        } else if (v == stopPlaybackButton) {

          stopService(playbackServiceIntent);

        }
      }
    }

BackgroundAudioService.java

package com.example.musicplayer;
import java.io.IOException;

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

public class BackgroundAudioService extends Service implements OnCompletionListener {
  MediaPlayer mediaPlayer;
  String data;

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

  @Override
  public void onCreate() {

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) { 

      data=(String) intent.getExtras().get("song_link");
      try {
        mediaPlayer.setDataSource(data);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (!mediaPlayer.isPlaying()) {
      mediaPlayer.start();
    }
    return START_STICKY;
  }

  public void onDestroy() {
    if (mediaPlayer.isPlaying()) {
      mediaPlayer.stop();
    }
    mediaPlayer.release();
  }

  public void onCompletion(MediaPlayer _mediaPlayer) {
    stopSelf();
  }

}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Background Audio Player"
        />
   <Button android:text="Start Playback" android:id="@+id/StartPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
   <Button android:text="Stop Playback" android:id="@+id/StopPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

3 个答案:

答案 0 :(得分:0)

首先,您的MediaPlayer未初始化,因此崩溃。

这里试试这个:

   package com.example.musicplayer;
    import java.io.IOException;

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

    public class BackgroundAudioService extends Service implements OnCompletionListener {
      MediaPlayer mediaPlayer;
      String data;

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

      @Override
      public void onCreate() {

      }
private void initMedia(String data) {
        mediaPlayer= MediaPlayer.create(BackgroundAudioService.this, Uri.parse(data));
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnCompletionListener(this);
    }



      @Override
      public int onStartCommand(Intent intent, int flags, int startId) { 
     if (intent == null || intent.getExtras() == null) // because this will             //start also first time you run the service even with no extras
        return;

          data=(String) intent.getExtras().get("song_link");
          if(mediaPlayer ==null)
            initMedia(data);
        else {
            mediaPlayer.setDataSource(data);
        }
        if (!mediaPlayer.isPlaying()) {
          mediaPlayer.start();
        }
        return START_STICKY;
      }

      public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
          mediaPlayer.stop();
        }
        mediaPlayer.release();
      }

      public void onCompletion(MediaPlayer _mediaPlayer) {
        stopSelf();
      }

    }

PS没有尝试过,但它只是一个指南;)

答案 1 :(得分:0)

请替换代码

@Override
  public void onCreate() {

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
  }

@Override
    public void onCreate()
    {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnCompletionListener(this);
    }

在mediaPlayer.start()之前添加以下行;在线服务。

mediaPlayer.prepare();

答案 2 :(得分:0)

因为您使用在线资源,您需要缓冲
你也应该在开始之前致电mediaPlayer.prepareAsync()mediaPlayer.prepare()可能需要很长时间 同样的问题: https://stackoverflow.com/a/15776134/3487232