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();
}
}
Related
I am trying to play a MediaPlayer from a activity, which was OPENED BY A BROADCAST RECEIVER. This works fine, if I play an internal file from the R.raw folder. But if I try to access a Mp3 file via a URI, it doesn't work anymore.
public class AlarmScreen extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_screen);
mediaPlayer = new MediaPlayer();
startMusic();
}
private void startMusic() {
String stringUri = element.getUri();
if (!(stringUri.equals(""))){
Uri uri = Uri.parse(stringUri);
mediaPlayer = MediaPlayer.create(this, uri);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
}, 1000);
}
}
The Error I get looks like this:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
I also tried to make the Media Player the following way, but it led to the same result:
Uri uri = Uri.parse(stringUri);
try {
mediaPlayer.setDataSource(this, uri);
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
}, 300);
I guess that the problem lies somewhere within the permissions, because as far as I know the BroadCastReceivers don't have the same permissions as the normal apps.
If you need more code, please let me know.
EDIT:
I have narrowed down the problem by making the following test-project:
Here 2 Uris are created. For Uri1, I use the data from the chooser. For Uri2 I use the Uri-String from a previous round. Then these Uris are played in the start(). If I play Uri1, it works always. But if I play Uri2, it only works if Uri1 is equal to Uri2. This is only the case if the same music-file is chosen in the chooser again, as in the round where I originally copied Uri2.
I really don't understand what I'm doing wrong. Is there another way, to access music-files from your device?
private void play(){
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(this, uri2);
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
mediaPlayer.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uri2 = Uri.parse("content://com.android.providers.media.documents/document/audio%3A17207");
uri1 = data.getData();
String str = uri.toString();
}
private void start(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(Intent.createChooser(intent, "choose:"), 1);
}
I think your problem is because of permissions.
Try to add the READ_EXTERNAL_STORAGE to your manifest.
Something like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
<application ...>
...
</application>
</manifest>
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.
I'm changing a lock screen using Service and BroadcastReceiver.
It change native lock sreen to custom perfectly, but I can't change to native again. How can I do it? Should I somehow disable Service or BroadcastReceiver?
code within Service
if(isMustBeLocked) {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new LockScreenReceiver();
registerReceiver(mReceiver, filter);
super.onCreate();
}
code within code within BroadcastReciever
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
if(!LockScreenService.isMustBeLocked) {
// need to do something here
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent intent11 = new Intent(context,LockScreenActivity.class);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} else if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
}
}
I am developing an App where I want to play two mp3 files one is background music and another audio plays after 20 seconds.
mediaPlayer = MediaPlayer.create(this, R.raw.testsong_20_sec);
mediaPlayer1 = MediaPlayer.create(this,R.raw.sound3 );
private void buttonClick(){
if (buttonPlayStop.getText() == getString(R.string.play_str)) {
buttonPlayStop.setText(getString(R.string.pause_str));
try
{
mediaPlayer.start();
mediaPlayer1.start();
startPlayProgressUpdater();
}
catch (IllegalStateException e) {
mediaPlayer.pause();
}
}
Use MediaPlayer to play background music and SoundPool for everything else.
You can play two files in Mediaplayer by using this piece of code in a thread(don't use UI thread for this) :
mediaplayer = new MediaPlayer();
mediaplayer.reset();
//For media file 1
mediaplayer.setDataSource(dataSourceOne);
mediaplayer.prepare();
mediaplayer.start();
Thread.sleep(500);//Set the time as per your need.
//For media file 2
mediaplayer.reset();
mediaplayer.setDataSource(dataSourceTwo);
mediaplayer.setLooping(true);
mediaplayer.prepare();
mediaplayer.start();
As per the better implementation perspective, write an util class with all the common methods (play(),pause(),stop()) and call every method from your class based on the requirement using a thread.
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.