Can someone tell me why my app keeps crashing? In debug it says "mediaplayer=null"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
play = findViewById(R.id.btn_play);
exit = findViewById(R.id.btn_exit);
settings = findViewById(R.id.btn_settings);
soundbutton = findViewById(R.id.btn_sound_main);
displayPlayername = findViewById(R.id.TextViewPlayerName);
//Display PlayerName - Setup in Settings
if (!Helper.getPlayerName(this).equals("Player"))
displayPlayername.setText(Helper.getPlayerName(this));
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play();
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeApp();
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openSettings();
}
});
// toogle Soundbutton Image and Sound
soundbutton.setOnClickListener(view -> {
if (Helper.getSound(this)) {
soundbutton.setImageResource(R.drawable.volume_off_white);
BackgroundPlayer.mediaPlayer.pause();
Helper.setSound(this, false);
} else {
soundbutton.setImageResource(R.drawable.volume_on_white);
BackgroundPlayer.mediaPlayer.start();
Helper.setSound(this, true);
}
});
}
public void play() {
Intent intent = new Intent(this, LobbyActivity.class);
startActivity(intent);
}
public void closeApp() {
finishAndRemoveTask();
//finish();
//System.exit(0);
}
public void openSettings() {
Intent intent = new Intent(this, SettingActivity.class);
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
if (Helper.getSound(this)) {
soundbutton.setImageResource(R.drawable.volume_on_white);
BackgroundPlayer.mediaPlayer.start();
} else {
soundbutton.setImageResource(R.drawable.volume_off_white);
}
}
#Override
public void onPause() {
super.onPause();
BackgroundPlayer.mediaPlayer.pause();
}
#Override
public void onDestroy() {
super.onDestroy();
BackgroundPlayer.mediaPlayer.stop();
}
public class BackgroundPlayer extends Application {
public static MediaPlayer mediaPlayer;
#Override
public void onCreate() {
super.onCreate();
setMediaPlayer();
}
public void setMediaPlayer() {
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.backgroundmusic);
mediaPlayer.setLooping(true);
if (Helper.getSound(this)) {
mediaPlayer.start();
} else {
mediaPlayer.start();
mediaPlayer.pause();
}
}
}
Related
This is my second activity and when open this activity threw button activity take load and open after some time and some times UI Freeze and some time black screen open for some seconds
public class AartiActivity extends AppCompatActivity {
final MediaPlayer player1 = new MediaPlayer();
private Button btn_playarti, btn_pausearti, btn_stoparti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aarti);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
btn_playarti = (Button) findViewById(R.id.btn_playarti);
btn_pausearti = (Button) findViewById(R.id.btn_pausearti);
btn_stoparti = (Button) findViewById(R.id.btn_stoparti);
try {
player1.setDataSource(STRING_URL);
player1.prepare();
} catch (IOException e) {
e.printStackTrace();
}
btn_playarti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) {
player.stop();
}
});
player1.start();
}
});
btn_pausearti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (player1.isPlaying()) {
player1.pause();
}
}
});
btn_stoparti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player1.stop();
}
});
}
#Override
protected void onStop() {
super.onStop();
player1.stop();
}
}
I'm trying to implement live stream radio by using fragment and background service, however every time I click to radio button on navigation drawer I couldn't reach the player because it generates one more and I can only control the second one. Here is my fragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_radio, container, false);
init(v);
ApiManager.getInstance().getRadioBroadcast(new ApiResponseLive.GetLiveBroadcastListener() {
#Override
public void onSuccess(StreamModel days) {
turnRadioOn(ApiManager.streamModel);
}
#Override
public void onFailure(String responseString) {
}
});
registerHandler(v);
return v;
}
private void turnRadioOn(StreamModel streamModel) {
HashMap<Integer, ArrayList<GenericStreamItem>> broadcastDays = new HashMap<>();
streamModel.setStreamAllArrays(broadcastDays);
BroadcastPagerAdapter radioPagerAdapter = new BroadcastPagerAdapter(getChildFragmentManager(), getContext(), TAG);
radioPager.setAdapter(radioPagerAdapter);
}
private void init(View v) {
radioPager = (ViewPager) v.findViewById(R.id.broadcastRadioPager);
radioTabLayout = (TabLayout) v.findViewById(R.id.tabsDays);
radioTabLayout.setupWithViewPager(radioPager);
radioPlay = (ToggleButton) v.findViewById(R.id.playButton);
radioScrollView = (ScrollView) v.findViewById(R.id.radioScroll);
}
private void start(String url) {
try {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setDataSource(url);
mp.prepareAsync();
mp.setOnCompletionListener(this);
Log.e("Radio::", "Working");
} catch (Exception e) {
Log.e("StreamAudioDemo", e.getMessage());
e.printStackTrace();
}
}
private void stop() {
try {
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void stopRadio() {
try {
Log.e("stopRadio::", "Pause");
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
}
private void registerHandler(View v) {
radioPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.e("Toggle::", "Enabled");
radioService = new RadioService();
radioService.initMediaPlayer(ApiManager.RADIO_URL);
} else {
Log.e("Toggle::", "Disabled");
stop();
stopRadio();
radioService.onDestroy();
}
}
});
v.findViewById(R.id.radioBroadcast).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public class RadioService extends Service implements MediaPlayer.OnErrorListener {
public void initMediaPlayer(String url) {
// ...initialize the MediaPlayer here...
ApiManager.getInstance().getRadioURL(new ApiResponseLive.GetTVStreamUrlListener() {
#Override
public void onSuccess(String tvUrl) {
start(ApiManager.RADIO_URL);
mp.setOnErrorListener(RadioService.this);
}
#Override
public void onFailure(String responseString) {
}
});
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
mp.reset();
return false;
}
#Override
public void onDestroy() {
if (mp != null) mp.release();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
}
Here is how I call fragment:
RadioFragment radioFragment = new RadioFragment();
fragment = fm.findFragmentByTag("radio");
radioDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fragment == null) {
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.activity_content))
.add(R.id.activity_content, radioFragment,
"radio").addToBackStack("main").commit();
} else {
fm.beginTransaction().replace(R.id.activity_content,
radioFragment, "radio");
}
fullView.closeDrawers();
}
});
I have created android app to stream online radio station and I want to run it in background using service.How to create service to run media player in background?
Here is source code of the application:
public class MainActivity extends AppCompatActivity
{
private ImageButton buttonPlay,buttonStop,buttonPause;
private String STREAM_URL = "http://178.149.86.162:8000/";
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);
buttonStop = (ImageButton) findViewById(R.id.buttonStopPlay);
buttonPause = (ImageButton) findViewById(R.id.buttonPause);
mPlayer = new MediaPlayer();
buttonPlay.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
mPlayer.reset();
mPlayer.setDataSource(STREAM_URL);
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
startService();
}
});
buttonStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mPlayer.stop();
stopService();
}
});
buttonPause.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mPlayer.pause();
stopService();
}
});
playbackServiceIntent = new Intent(this, BackgroundService.class);
}
private void startService()
{
startService(new Intent(MainActivity.this,BackgroundService.class));
}
private void stopService()
{
stopService(new Intent(MainActivity.this,BackgroundService.class));
}
}
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL = "http://178.149.86.162:8000/";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
mediaPlayer = new MediaPlayer();
try
{
mediaPlayer.setDataSource(STREAM_URL);
} catch (IOException e)
{
e.printStackTrace();
}
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
i'am trying to develop an app which, when you enter in home screen you can listen a music until you enter in other activity. It Nothing works, and i don't know why...
my code :
public class MainActivity extends Activity {
Button jugar, preferencias, acercade, maximo, salir;
Vibrator v;
Boolean isVibrar,sonido;
MediaPlayer sonidoJuego;
ThreadSonido threadSonido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_land);
v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
isVibrar = sharedPref.getBoolean("vibracion", false);
sonido=sharedPref.getBoolean("musica", true);
if(sonido==true){
threadSonido.start();
}else{
threadSonido.stop();
}
}
public void dentroJuego(View view) {
if (isVibrar==true) {
v.vibrate(100);
}
Intent i = new Intent(MainActivity.this, AngryJuego.class);
startActivity(i);
this.finish();
}
public void salir(View view) {
sonidoJuego.stop();
finish();
}
public void preferencias(View view) {
if (isVibrar==true) {
v.vibrate(100);
}
Intent i = new Intent(MainActivity.this, Preferencias.class);
startActivity(i);
}
public void maximosRegistros(View view) {
if (isVibrar==true) {
v.vibrate(100);
}
Intent i = new Intent(MainActivity.this, MaximosRegistros.class);
startActivity(i);
}
public void lanzarAcercaDe(View view) {
if (isVibrar==true) {
v.vibrate(100);
}
Intent i = new Intent(this, AcercaDe.class);
startActivity(i);
}
public void recargar(){
Intent i= this.getIntent();
finish();
startActivity(i);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
finish();
}
public class ThreadSonido extends Thread {
#Override
public void run() {
sonidoJuego=MediaPlayer.create(getBaseContext(),R.raw.gaitas);
sonidoJuego.setLooping(true);
sonidoJuego.start();
}
}
}
And the log
05-10 14:08:23.800: E/AndroidRuntime(12283): FATAL EXCEPTION: main
05-10 14:08:23.800: E/AndroidRuntime(12283): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sergiochuky.angryfaba/com.example.game.MainActivity}: java.lang.NullPointerException
i have 2 activities. and 2 different background music plays on both. when i press a button on the first activity it will go to this activity and the changing of music goes smoothly but i want to stop background music when back button is pressed. i tried this but it force closes. is there any other way to do this?
public class Categories extends Activity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
mp = MediaPlayer.create(Categories.this, R.raw.looney);
mp.setLooping(true);
mp.start();
Button cartoonButton = (Button) findViewById(R.id.cartoon);
cartoonButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchCartoon = new Intent(Categories.this, Cartoon.class);
startActivity(launchCartoon);
}
});
Button superButton = (Button) findViewById(R.id.hero);
superButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent launchSuperheroes = new Intent(Categories.this, SuperHeroes.class);
startActivity(launchSuperheroes);
}
});
Button singerButton = (Button) findViewById(R.id.singer);
singerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchSinger = new Intent(Categories.this, Singer.class);
startActivity(launchSinger);
}
});
Button famousButton = (Button) findViewById(R.id.famous);
famousButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent launchFamous = new Intent(Categories.this, Famous.class);
startActivity(launchFamous);
}
});
}
#Override
protected void onResume() {
super.onResume();
mp.start();
}
#Override
protected void onPause() {
super.onPause();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
You can try this code:
#Override
public void onBackPressed() {
if (player.isPlaying()) {
player.stop();
}
player.release();
super.onBackPressed();
}
Hope this help you :)