Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hi I was following a tutorial I found to make an app that plays a radio, the app works until you exit because then the sound stops. I have researched and found out that it needs to be a service but I am not sure how to change it to a service, this is the code I used.
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
I tried changing it but I am not sure how to put the functions from the main activity into a new service and then run it.
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mMediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
} // initialize it here
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}
I tried using the above code but I do not know how to start the action and whether or not it will work.
Thank you for reading :)
Call a service from your main activity.
startService(new Intent(MusicService.ACTION_PLAY));
your service class.
public class MusicService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_PLAY))
processPlayRequest();
return START_STICKY;
}
Related
I am trying to run my Android radio app in the background. So when I click the back button after a little time it has been forced to stop. Automatically calls the onDestroy() method. How do I fix this problem?
This is the main activity class onBackPressed() button code.
#Override
public void onBackPressed(){
System.out.println("onBackPressed");
serviceIntent.addCategory(Intent.CATEGORY_HOME);
serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(serviceIntent);
moveTaskToBack(true);
//activity.moveTaskToBack(true);
}
This is the console log
> I/System.out: onPrepared I/System.out: onBackPressed I/System.out:
> onDestroy I/System.out: onDestroy1 I/System.out: onDestroy2
> V/MediaPlayer: resetDrmState: mDrmInfo=null
> mDrmProvisioningThread=null mPrepareDrmInProgress=false
> mActiveDrmScheme=false V/MediaPlayer: cleanDrmObj: mDrmObj=null
> mDrmSessionId=null W/MediaPlayer: mediaplayer went away with unhandled
> events
MainActivity
package com.jiat.yesradio;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements MusicStoppedListener {
private ImageView imagePlayPause;
String stream = "https://radio.lankayes.lk/8002/stream";
boolean musicPlaying = false;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("onCreate MainA");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePlayPause = (ImageView) findViewById(R.id.imagePlayPause);
imagePlayPause.setImageResource(R.drawable.play_icon);
serviceIntent = new Intent(this, MyPlayService.class);
// serviceIntent = new Intent(this, SimpleMyPlayService.class);
ApplicationClass.context = (Context) MainActivity.this;
imagePlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("onClick");
if (!musicPlaying) {
System.out.println("onClick_inside_music_player");
startService(serviceIntent);
playAudio();
imagePlayPause.setImageResource(R.drawable.pause_icon);
musicPlaying = true;
}
else {
stopPlayService();
stopService(serviceIntent);
imagePlayPause.setImageResource(R.drawable.play_icon);
musicPlaying = false;
}
}
});
}
#Override
public void onBackPressed(){
System.out.println("onBackPressed");
/* serviceIntent.addCategory(Intent.CATEGORY_HOME);
serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(serviceIntent);*/
moveTaskToBack(true); //activity.moveTaskToBack(true);
}
private void stopPlayService() {
System.out.println("stopPlayService");
try {
stopService(serviceIntent);
} catch (SecurityException e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void playAudio() {
System.out.println("playAudio");
serviceIntent.putExtra("AudioLink", stream);
// serviceIntent.putExtra("SimpleAudioLink", stream);
try {
startService(serviceIntent);
} catch (SecurityException e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onMusicStopped() {
System.out.println("onMusicStopped");
imagePlayPause.setImageResource(R.drawable.play_icon);
musicPlaying = false;
}
}
MyPlayService class.
package com.jiat.yesradio;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class MyPlayService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnInfoListener,
MediaPlayer.OnBufferingUpdateListener {
private MediaPlayer mediaPlayer;
String link;
private MusicStoppedListener musicStoppedListener;
Context context;
public MyPlayService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
System.out.println("onBind");
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setLooping(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
link = intent.getStringExtra("AudioLink");
mediaPlayer.reset();
musicStoppedListener = (MusicStoppedListener) ApplicationClass.context;
if (!mediaPlayer.isPlaying()) {
try {
mediaPlayer.setDataSource(link);
mediaPlayer.prepareAsync();
} catch (Exception e) {
Toast.makeText(this, "Error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("onDestroy");
if (mediaPlayer != null) {
System.out.println("onDestroy1");
if (mediaPlayer.isPlaying()) {
System.out.println("onDestroy2");
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
System.out.println("onBufferingUpdate");
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
/* if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
musicStoppedListener.onMusicStopped();
stopSelf();*/
System.out.println("onCompletion");
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int i1) {
System.out.println("onError");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this, "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA_ERROR_SERVER_DIED", Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA_ERROR_UNKNOWN", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
System.out.println("onInfo");
return false;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
System.out.println("onPrepared");
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
#Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
System.out.println("onSeekComplete");
}
}
Can anyone help me debug which part of my code is the reason why it keeps crashing? I've been trying to figure out which part is wrong, I got the code online and applied it on my own but I had troubles on this part where it keeps saying app is
I created different functions to figure out which part is wrong, thank you.
in my logcat it says:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.intern()' on a null object reference
Mainactivty
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextView tv_time;
private TextView tv_amount;
private ImageView iv_status_01;
private ImageView iv_status_02;
private ImageView iv_status_03;
private ImageView iv_status_04;
private ImageView iv_status_05;
private ImageView iv_status_06;
private ImageView iv_complete;
private Intent serviceInent = null;
public static String status1;
public static String status2;
public static String status3;
public static String status4;
public static String status5;
public static String status6;
private IntentFilter intentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction(status1);
intentFilter.addAction(status2);
intentFilter.addAction(status3);
intentFilter.addAction(status4);
intentFilter.addAction(status5);
intentFilter.addAction(status6);
init();
}
private void init(){
tv_amount = findViewById(R.id.tv_amount);
tv_time = findViewById(R.id.tv_time);
Date date = new Date();
Locale philippineLocale = new Locale.Builder().setLanguage("en").setRegion("PH").build();
tv_time.setText(getDate(date, philippineLocale));
tv_amount.setText("Total Amount :\n500.00");
serviceInent = new Intent(this, DeliveryService.class);
startService(new Intent(this, DeliveryService.class));
}
private String getDate(Date date, Locale locale) {
DateFormat formatter = new SimpleDateFormat("EEEE \nMMMM dd, yyyy", locale);
return formatter.format(date);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, intentFilter);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(status1)) {
iv_status_01.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status2)) {
iv_status_02.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status3)) {
iv_status_03.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status4)) {
iv_status_04.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status5)) {
iv_status_05.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status5)) {
iv_status_06.setImageResource(R.drawable.box_check);
}
}
};
#Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
}
Deliveryservice:
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
public class DeliveryService extends Service {
private String LOG_TAG = null;
#Override
public void onCreate() {
super.onCreate();
LOG_TAG = this.getClass().getSimpleName();
Log.i(LOG_TAG, "In onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "In onStartCommand");
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.status1);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status2);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status3);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status4);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status5);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status6);
sendBroadcast(broadcastIntent);
}
}).start();
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
Log.i(LOG_TAG, "In onBind");
return null;
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(LOG_TAG, "In onTaskRemoved");
}
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
}
thank you.
You should initialize strings used as Action (like status1); otherwise, NullProinterException will be thrown.
I want to show the progress of the music played in the seekbar. I am not able to do so. Please help!
I am not understanding what's the problem here. I am very much new to programming. I am actually trying to build an app that can play music and the music progress is displayed on the seekbar
package com.example.musicapp;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
MediaPlayer startmusic;
SeekBar seekBar;
ImageButton play;
ImageButton pause;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=findViewById(R.id.play_button);
seekBar=findViewById(R.id.seekBar);
pause=findViewById(R.id.pause_button);
startmusic=MediaPlayer.create(this,R.raw.music);
}
public void playmusic(View v){
startmusic.start();
play.setImageResource(R.drawable.pause);
play.setVisibility(play.GONE);
pause.setVisibility(pause.VISIBLE);
seekBar.setMax(startmusic.getDuration());
Toast toast=Toast.makeText(getApplicationContext(),"Music is playing", Toast.LENGTH_SHORT);
toast.show();
changeSeekbar();
}
private void changeSeekbar() {
if(startmusic.isPlaying()){
seekBar.setProgress(startmusic.getCurrentPosition());
runnable=new Runnable() {
#Override
public void run() {
changeSeekbar();
handler.postDelayed(runnable,100);
}
};
}
}
public void pausemusic(View v){
if(startmusic.isPlaying()) {
startmusic.pause();
play.setImageResource(R.drawable.pause);
play.setVisibility(play.VISIBLE);
pause.setVisibility(pause.GONE);
seekBar.setProgress(startmusic.getCurrentPosition());
Toast toast=Toast.makeText(getApplicationContext(),"Music is paused", Toast.LENGTH_SHORT);
toast.show();
}
}
}
You can use the common methods of the MediaPlayer class in order to show the progress:
start()
stop()
release() – To prevent memory leaks.
seekTo(position) – This will be used with the SeekBar
isPlaying() – Let us know whether the song is being played or not.
getDuration() – Is used to get the total duration. Using this we’ll
know the upper limit of our SeekBar. This function returns the
duration in milli seconds
setDataSource(FileDescriptor fd) – This is used to set the file to be played.
setVolume(float leftVolume, float rightVolume) – This is used to set
the volume level. The value is a float between 0 or 1.
<SeekBar
android:id="#+id/seekbar"
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
The code for the MainActivity.java class is given below:
public class MainActivity extends AppCompatActivity implements Runnable {
MediaPlayer startmusic;
SeekBar seekBar;
ImageButton play;
ImageButton pause;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=findViewById(R.id.play_button);
seekBar=findViewById(R.id.seekBar);
pause=findViewById(R.id.pause_button);
startmusic=MediaPlayer.create(this,R.raw.music);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekBarHint.setVisibility(View.VISIBLE);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
seekBarHint.setVisibility(View.VISIBLE);
int x = (int) Math.ceil(progress / 1000f);
if (x == 0 && startmusic != null && !startmusic.isPlaying()) {
clearMediaPlayer();
MainActivity.this.seekBar.setProgress(0);
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (startmusic != null && startmusic.isPlaying()) {
startmusic.seekTo(seekBar.getProgress());
}
}
});
}
//its look that you call this method form layout itself
//change your play method defination to
public void playmusic(View v) {
try {
play.setImageResource(R.drawable.pause);
play.setVisibility(play.GONE);
pause.setVisibility(pause.VISIBLE);
Toast toast=Toast.makeText(getApplicationContext(),"Music is playing", Toast.LENGTH_SHORT);
toast.show();
if (startmusic == null) {
startmusic = new MediaPlayer();
}
AssetFileDescriptor afd = context.getResources().openRawResourceFd(/*your raw id resource*/);
if (afd == null)
return;
startmusic.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
startmusic.prepare();
startmusic.setVolume(0.5f, 0.5f);
startmusic.setLooping(false);
seekBar.setMax(startmusic.getDuration());
startmusic.start();
new Thread(this).start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void pausemusic(View v) {
//add null check
if(startmusic != null && startmusic.isPlaying()) {
startmusic.pause();
play.setImageResource(R.drawable.pause);
play.setVisibility(play.VISIBLE);
pause.setVisibility(pause.GONE);
seekBar.setProgress(startmusic.getCurrentPosition());
Toast toast=Toast.makeText(getApplicationContext(),"Music is paused", Toast.LENGTH_SHORT);
toast.show();
}
}
public void run() {
int currentPosition = startmusic.getCurrentPosition();
int total = startmusic.getDuration();
if (currentPosition == total) {
clearMediaPlayer();
}
while (startmusic != null && startmusic.isPlaying() && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = startmusic.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
clearMediaPlayer();
}
private void clearMediaPlayer() {
startmusic.stop();
startmusic.release();
startmusic = null;
}
}
I am not sure where I have missed something, I expect the playPauseButton to respond when I click it but nothing happens when I do. I have noticed some errors in my debug console log, which are mostly related to mediaPlayer, but I don't exactly know what they mean, since an quite new to android programming! Below is my debug console log, and a bit of related code:
// Removed Logcat!!
Some code related from a class Player.java:
import android.media.MediaPlayer;
import android.media.AudioManager;
import android.util.Log;
import java.io.IOException;
public class Player {
// Creating new MediaPlayer
MediaPlayer mediaPlayer = new MediaPlayer();
// Creating a public static player as reference to this Player class
public static Player player;
String url = "";
public Player () {
this.player = this;
}
public void playStream (String url) {
if (mediaPlayer != null) {
try {
mediaPlayer.stop();
} catch (Exception e) {
}
// Releasing everything from the mediaPlayer
mediaPlayer = null;
}
// Creating new Media Player
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// Try & Catch errors
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
public void pausePlayer () {
try {
mediaPlayer.pause();
} catch (Exception e) {
Log.d("EXCEPTION", "Failed to pause Media Player");
}
}
public void playPlayer () {
try {
mediaPlayer.start();
} catch (Exception e) {
Log.d("EXCEPTION", "Failed to start Media Player");
}
}
public void togglePlayer () {
try {
if (mediaPlayer.isPlaying())
pausePlayer();
else
playPlayer();
} catch (Exception e) {
Log.d("Exception", "Failed to toggle Media Player");
}
}
}
the other related code from MainActivity.java
public class MainActivity extends AppCompatActivity {
static FloatingActionButton playPauseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playPauseButton = (FloatingActionButton) findViewById(R.id.fab);
playPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Songs location on our server
String url = // "*My website/file.mp3";
// Passing above url to our MediaPlayer
if (Player.player == null)
new Player();
Player.player.playStream(url);
}
public static void flipPlayPauseButton (boolean isPlaying) {
if (isPlaying) {
playPauseButton.setImageResource(android.R.drawable.ic_media_pause);
} else {
playPauseButton.setImageResource(android.R.drawable.ic_media_play);
}
}
Try for example:
playPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(video.isplaying()){pause function()}
else{play function()}
}
});
Okay, I'd like to thank MohammadMoeinGolchin, who has helped me figure this out. It so happen's that I did not complete my function inside of my public void onClik(View view) function. But you will see that is is written somewhere in a separate Player.java class. So to resolve this, what I did instead, is to call the togglePlayer() function inside my onClick(View view) like this:
#Override
public void onClick (View view) {
Player.player.togglePlayer();
}
I successfully implemented AdMob interstitial ads into my application but the only problem is that they are not clickable.
Here is my AdMob.java class:
import android.app.Activity;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
public class Admob extends AdListener{
private Activity ctx;
//Admob
private InterstitialAd interstitial;
private AdRequest adRequest;
private String unitId;
public static boolean fromAdmob = false;
public Admob(Activity ctx, String unitId)
{
this.ctx = ctx;
this.unitId = unitId;
try{
this.interstitial = new InterstitialAd(this.ctx);
interstitial.setAdUnitId(unitId);
interstitial.setAdListener(this);
adRequest = new AdRequest.Builder().build();
}
catch (Exception e){
e.printStackTrace();
}
}
public void loadAd()
{
try{
interstitial.loadAd(adRequest);
}
catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onAdLoaded() {
try{
fromAdmob = true;
interstitial.show();
}
catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onAdFailedToLoad(int errorCode)
{
}
#Override
public void onAdClosed() {
fromAdmob = false;
}
}
And the MainPageActivity.java file:
public class MainPageActivity extends Activity implements IGameListener, IEventDelegate{
//Tags
private static final String TAG = "bubblesMainPage";
//Context
public static Activity instance;
//Media
private MediaPlayer mp;
//Ads
private Admob admob;
//TapSDK
private Tap tap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_activity);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
tr
Tap.establish(this);
tap = new Tap(this, "xxxx");
}
catch (Exception e){
e.printStackTrace();
}
//Admob
this.admob = new Admob(this, "ADMOB_ID");
//Context
instance = this;
//Media
mp = MediaPlayer.create(getApplicationContext(), R.raw.background_music);
mp.setLooping(true);
//Set activity properties
try {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} catch (Exception e) {
e.printStackTrace();
}
//Intents & Listeners
final Intent gamePlayActivity = new Intent(this, BubbleShooterActivity.class);
BubbleShooterActivity.listener = this;
//Animations
Animation scaleUpAnim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale_up);
findViewById(R.id.play_button).startAnimation(scaleUpAnim);
//UI Events
findViewById(R.id.play_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
try {
startActivity(gamePlayActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
findViewById(R.id.more_games_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tap.showMoreGamesWithViewControllerAndAppID((IEventDelegate)instance);
}
});
}
/*
Game methods - start
*/
#Override
public void onGameStart() {
Log.i(TAG, "onGameStart");
}
#Override
public void onLevelFailed() {
//Level failed window
try{
Intent i = new Intent(this, LostActivity.class);
startActivity(i);
}
catch (Exception e){
e.printStackTrace();
}
Log.i(TAG, "onLevelFailed");
}
#Override
public void onLevelUp() {
Log.i(TAG, "onLevelUp");
if(admob != null){
runOnUiThread(new Runnable() {
#Override
public void run() {
try{
admob.loadAd();
}
catch (Exception e){
e.printStackTrace();
}
try{
Intent i = new Intent(instance, WonActivity.class);
startActivity(i);
}
catch (Exception e){
e.printStackTrace();
}
}
});
}
}
#Override
public void onGameEnd() {
Log.i(TAG, "onGameEnd");
}
/*
TapSDK methods - start
*/
#Override
public void viewDidAppear() {
Log.i(TAG, "TapSDK: viewDidAppear");
}
#Override
public void viewDidDisappear() {
Log.i(TAG, "TapSDK: viewDidDisappear");
}
#Override
public void viewConnectFail(String s) {
Log.i(TAG, "TapSDK: viewConnectFail " + s);
}
#Override
public void conversion() {
Log.i(TAG, "TapSDK: conversion");
}
#Override
public void onOfferComplete(int score) {
Log.i(TAG, "TapSDK: onOfferComplete " + score);
}
/*
Activity methods start
*/
#Override
public void onBackPressed() {
Log.i(TAG, "onBackPressed");
try{
Intent exitScreen = new Intent(this, ExitActivity.class);
startActivity(exitScreen);
}
catch (Exception e){
e.printStackTrace();
Log.e(TAG, "onBackPressed: " + e.getMessage());
}
}
#Override
protected void onStart() {
super.onStart();
// Monitor launch times and interval from installation
RateThisApp.onStart(this);
// If the criteria is satisfied, "Rate this app" dialog will be shown
RateThisApp.showRateDialogIfNeeded(this);
}
#Override
protected void onResume()
{
super.onResume();
if(tap != null)
tap.onResume();
mp.seekTo(0);
mp.start();
}
#Override
protected void onPause()
{
if(tap != null)
tap.onPause();
mp.pause();
super.onPause();
}
#Override
protected void onDestroy()
{
mp.stop();
mp = null;
if(tap != null)
tap.onDestroy();
super.onDestroy();
}
}
I couldn't figure out how to show the interstitial ad when the user levels up and presses the play button (which will lead him to the next level). The interstitial ad show up when he presses the home button which will take him to the MainActivity screen.
Can someone help me to make the ads clickable? Also, any suggestions on how to add the interstitial ad after each completed level? When someone has finished a level and presses the play button, an interstitial ad should appear and when that is closed he should be able to play the next level.
I really appreciate your help!
A number of issues:
Don't call interstitial.show() from onAdLoaded. Call show() when the user presses the play button for your next level (but only if an ad is available).
Get rid of public static Activity instance; Never hold a static reference to an Activity. You will just leak context everywhere.
Instead of calling admob.loadAd() from onLevelUp() call it as soon as you create your Activity (it takes times to load an ad from the network). NB you don't need to call it from runOnUIThread()
Call admob.loadAd() again after each time you show the ad to the user.