Stop media player (initiated from a broadcast receiver ) from an activity android - java

I have an AlarmManager that notifies a broadcast receiver and the broadcast receiver plays a rigntone using the MediaPlayer class. when The alarm fires I have an activity that launches and have an OK button that should stop the media player. the question is how can I access the media player from the activity so I can stop it.
my code is as follow:
public void onReceive(Context context, Intent intent) {
// some other code........
try
{
MediaPlayer mediaPlayer = playAlarm(context, fileName);
createAlarmNotificationDialog(context, mediaPlayer);
}
catch ( Exception ex)
{
ex.printStackTrace();
}
}
}
private MediaPlayer playAlarm(Context context, String fileName) throws IllegalStateException, IOException
{
File inputFile = new File("/sdcard/sampleringtone.mp3");
//File inputFile = new File("/system/media/audio/alarms/" + fileName + ".mp3");
FileInputStream fis = new FileInputStream(inputFile);
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fis.getFD());
//mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
return mediaPlayer;
}
private void createAlarmNotificationDialog(Context context, final MediaPlayer mediaPlayer)
{
Intent intent = new Intent(context, AlarmNotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}

Guys you can save mediaplayer instance in application class and access it from anywhere.
This will help you: How to declare global variables in Android?

I am also came across with the same problem. i solved it.Create a service class and declare the media player in that class. once the alarm fires, start the service class from broadcast receiver class and stop the service from any activity. hope so it helpful.
In broadcast receiver class
Intent serviceIntent = new Intent(context,MyService.class);
context.startService(serviceIntent);
from any of activity
stopService(new Intent (getApplicationContext(),MyService.class));

the question is how can I access the media player from the activity so I can stop it.
You can't. You leaked it. Since you are starting an activity, anyway, have it play the ringtone.

Related

How to vibrate with sound

I am trying to add sound while vibration.
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(2000);
}
Vibration Applied successfully, but how to add sound while phone vibrate?
You can easily do that using MediaPlayer.
Firstly, Create an instance of MediaPlayer class:
MediaPlayer mediaPlayer = new MediaPlayer();
Then, set the source file, in order to this, firstly place the audio file in res/raw folder of your Project directory, then use this code:
mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}");
Then play that file using this code:
mediaPlayer.prepare();
mediaPlayer.start();
Keep in mind that you have to put this code in try | catch block.
Now your whole code will be this:
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Get Ready Bus is Near",Toast.LENGTH_LONG).show();
// Initializing instance of Vibrator.
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Initializing instance of MediaPlayer.
MediaPlayer mediaPlayer = new MediaPlayer();
// Starting Vibration
v.vibrate(2000);
try {
// Setting the source of audio file.
mediaPlayer.setDataSource(context, Uri.parse("android.resource://{package name}/res/raw/{audio file name}"); // Fill the information accordingly.
mediaPlayer.prepare();
// playing audio.
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}

Pop up window after the alarm signal - Android

I would like to know - how to show pop up window when AlarmManager will call? I've already created AlarmManager now I need to create something what will show popup window to cancel this Alarm.
My code:
public void setAlarm(long timeInMillis){
if(Build.VERSION.SDK_INT >= 23){
mCalendar.set(
mCalendar.get(Calendar.MONTH),
mCalendar.get(Calendar.YEAR),
mCalendar.get(Calendar.DAY_OF_YEAR),
mCalendar.get(Calendar.HOUR_OF_DAY),
mCalendar.get(Calendar.MINUTE)
);
}
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarm.class);
intent.setData(currentUri);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setExact(AlarmManager.RTC, timeInMillis, pendingIntent);
}
and
public class MyAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
MediaPlayer mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
}
onReceive(context, intent) {
/*show the dialog in this method. set the onclick so it can dismiss the alarm,
get the value for the alarm from the bundle. I may be wrong about this
but i think alarmManager has a cancel(PendingIntent operation) method that u can
just send in the intent and your done.
Call a stopMedia(context) method after the cancel in order to stop the media
that is playing
*/
showDialog(context, intent)
//Extract the play media code to a method for readability
playMedia(context)
}
That should solve your problem
Before the code was posted:
We can either use the pending intent and have an activity that handles the pending intent. or use the handler to execute the code.
In either case, create a dialog fragment and then use the appropriate context to show it. setOnClickListener { alarmManager.cancel } for the dialog fragment button.
A little more explanation may be required depending on how the alarm manager is setup

How to pass parameters to Broadcast receiver class?

I have created a Broadcast receiver and it is working fine. but I need to pass a handler to that class.
public static class DataReceiver extends BroadcastReceiver {
Handler handler;
DataReceiver(Handler loghandler) {
this.handler = loghandler;
}
#Override
public void onReceive(Context context, Intent intent) {
//things goes here
}
}
Currently I am using like this & It is working if constructor override is not available.
Intent intent = new Intent(this, DataReceiver .class);
but I need to pass the handler too. How can I send the handler? Thanks
I don't really understand what you are trying to accomplish but i think this may help you. You don't need to make a whole new class for your broadcast receiver but you can use it inside your Main Activity like this:
BroadcastReceiver receiveLocationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Your custom action
}
};
IntentFilter receiveLocationFilter = new IntentFilter();
receiveLocationFilter.addAction("android.intent.RECEIVE_LOCATION");
Register the receiver in "onStart":
registerReceiver(receiveLocationReceiver, receiveLocationFilter);
Unregister it in "onStop":
unregisterReceiver(receiveLocationReceiver);
Then when you need to send the broadcast all you need is :
Intent sendBroadcastIntent = new Intent("android.intent.RECEIVE_LOCATION");
sendBroadcast(sendBroadcastIntent);

I have played a song when power connected, but it's not stopping when power is disconnected

I want to play a song when the power is connected, and stop the song when the power is disconnected, but this song still plays when the power is disconnected. Please share working code regarding this.
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(context, R.raw.mysong);
if (intent.getAction() == Intent.ACTION_POWER_CONNECTED) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
else if (intent.getAction() == Intent.ACTION_POWER_DISCONNECTED) {
Toast.makeText(context, "POWER DISCONNECTED !!!!!", Toast.LENGTH_SHORT).show();
mMediaPlayer.stop();
}
}
}
This Link will help you.
You have to register Broadcast for android.intent.action.ACTION_POWER_DISCONNECTED.
and than receive on of power disconnect broadcast stop you media player.
https://techcampuz.blogspot.in/2016/07/how-to-detect-when-power-connected-and.html
And your above code for every broadcast message Mediaplayer created new object so that me be problem, user that outside of the receiver method.

MediaPlayer stopping when starting another activity

I have a problem with the MediaPlayer.
I have a MediaPlayer class that starts as soon as the user launches the App, but as soon as the user taps on the "credits" button another activity starts with the credits screen, but the MediaPlayer stops playing the audio stream.
Is there a way to avoid this?
MediaPlayer setup:
player = new MediaPlayer();
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
I change page with this:
Intent intent = new Intent(this, Credits.class);
startActivity(intent);
Create a local service and put the MediaPlayer in that Service. Bind to the Service from whatever Activity needs to control the MediaPlayer.
This is not possible since the mediaActivity will be pause. You might consider using a dialog instead of an intent for the credits.

Categories

Resources