I have a app that plays radio via MediaPlayer as a service. Is it possible to use MediaController in Service class? The problem is that I can use findViewById.
I try to get my LinearLayout in onPrepeared methiod ...
public class RadioPlayer extends Service implements OnPreparedListener, MediaController.MediaPlayerControl {
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this, false); mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
}
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
mediaController.setMediaPlayer(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, (ViewGroup) findViewById(R.id.main_program_view));
mediaController.setAnchorView(layout);
}
}
main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_program_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<TextView
android:id="@+id/now_playing_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:text="@string/na_antenie"
android:textColor="#333333" />
</LinearLayout>
I had the same problem and I couldn't get it working the way you have it.
The solution is to bind the Service in the Activity and then you may access the MediaPlayer running in the Service from within your Activity.
Please note that to run this way your Service must have defined all necessary methods like getCurrentPosition etc.
In your Activity add the binding facility:
Then you must modify the onStart() and onStop() methods to Bind/unBind the service.
What I did later is to create the following methods
first is a boolean that is used to realize whether we have to create the mediacontroller or not, I create only on the first time the user touches the screen.