Stopping & Starting Music on Incoming Calls

Stopping & starting music on incoming calls

There are a few things you can do:

First of all, you can listen for changes in the call state using a PhoneStateListener.
You can register the listener in the TelephonyManager:

PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}

Remember to unregister the listener when it's no longer needed using the PhoneStateListener.LISTEN_NONE:

TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}

For more information read the documentation.

Another thing you can do is listening for the broadcast android.intent.action.PHONE_STATE. It will contain the extra TelephonyManager.EXTRA_STATE which will give you information about the call. Take a look at the documentation here.

Please note that you'll need the android.permission.READ_PHONE_STATE-permission in both cases.

How can I stop music on an incoming call?

You need to use the TelephonyManager

mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

The listener object can be created like this

private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
// Test for incoming call, dialing call, active or on hold
if (state==TelephonyManager.CALL_STATE_RINGING || state==TelephonyManager.CALL_STATE_OFFHOOK)
{
stop(); // Put here the code to stop your music
}
super.onCallStateChanged(state, incomingNumber);
}
};

When stopping, or closing your app, remember to call this.

mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);

stop and play music for incoming call

 private OnAudioFocusChangeListener focusChangeListener =
new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {

case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
mp.setVolume(0.2f, 0.2f);
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
mp.pause();
break;

case (AudioManager.AUDIOFOCUS_LOSS) :
mp.stop();

break;

case (AudioManager.AUDIOFOCUS_GAIN) :
// Return the volume to normal and resume if paused.
mp.setVolume(1f, 1f);
mp.start();
break;
default: break;
}
}
};

AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so u can do u stuff now .

}
}

Android closing media service on incoming call

you have to create receiver for incoming call like below:

public class call_reciver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String number = "";
Bundle bundle = intent.getExtras();

if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// Phone is ringing
number = bundle.getString("incoming_number");

} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
// Call received

} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
// Call Dropped or rejected

}

}

in manifest put this:

<receiver android:name=".call_reciver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>

permission :

<uses-permission android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>

make your media player variable static & globale, in reciver call another service to check your media player is running or not. if it is running then stop it. you can use also use same service.

you have to start services from receiver:

Intent myIntent = new Intent(context, Service_temp.class);
context.startService(myIntent);

in service use this:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}

check edited ans:

In below example I have done all things. there is one button it ll play song in service. at that time you receive in coming call then it will stop your service(stop playing song) and when you reject or drop call then it again start playing song

main Activity class :

package com.example.androidmediaplay;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

public void clickBtn(View v) {
if (v.getId() == R.id.button1) {
UtilClass.playing = true;
Intent i = new Intent(MainActivity.this,
BackgroundSoundService.class);
startService(i);
}
}

}

BackgroundSoundService class:

package com.example.androidmediaplay;

import java.io.File;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

public class BackgroundSoundService extends Service {

private static final String TAG = null;
MediaPlayer player;

public IBinder onBind(Intent arg0) {

return null;
}

@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(
this,
Uri.fromFile(new File(Environment.getExternalStorageDirectory()
+ "/Songs/test.mp3")));
player.setLooping(true); // Set looping
player.setVolume(100, 100);

}

public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("onStartCommand", "onStartCommand");
if (player.isPlaying()) {
player.pause();
UtilClass.pause = true;

Log.e("onStartCommand pause", "onStartCommand pause");
} else {
UtilClass.pause = false;
player.start();
}

return 1;
}

public void onStart(Intent intent, int startId) {
// TO DO
}

public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}

public void onStop() {

}

public void onPause() {

}

@Override
public void onDestroy() {
UtilClass.playing = false;
player.stop();
player.release();
}

@Override
public void onLowMemory() {

}

}

call receiver class:

package com.example.androidmediaplay;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;

public class call_reciver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String number = "";
Bundle bundle = intent.getExtras();

if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// Phone is ringing
number = bundle.getString("incoming_number");
Log.e("incoming_number", "incoming_number");
_stopServices(context);

} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
// Call received

} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
// Call Dropped or rejected
_stopServices(context);
}

}

private void _stopServices(Context con) {
// TODO Auto-generated method stub
if (UtilClass.playing == true) {
Log.e("start services", "start services");
Intent i = new Intent(con, BackgroundSoundService.class);
con.startService(i);
} else {
Log.e("start not services", "start not services");
}
}

}

extra class for static member:

package com.example.androidmediaplay;

public class UtilClass {

public static Boolean playing = false;
public static boolean pause = false;
}

in last manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidmediaplay"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidmediaplay.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service
android:name=".BackgroundSoundService"
android:enabled="true" >
</service>

<receiver android:name=".call_reciver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>

</manifest>

All code is working at my end. please check it and tell me.

swift start music after user phone call

You need to set your audio session to AVAudioSessionCategoryPlayback. If you don't set this mode, you will have the default mode AVAudioSessionCategorySoloAmbient.

You can set the mode in didFinishLaunching.

e.g.

func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

// Get the singleton instance.
let audioSession = AVAudioSession.sharedInstance()
do {
// Set the audio session category, mode, and options.
try audioSession.setCategory(.playback, mode: .default, options: [])
} catch {
print("Failed to set audio session category.")
}

// Other post-launch configuration.
return true
}

You will also need to implement interruption observation

func setupNotifications() {
// Get the default notification center instance.
let nc = NotificationCenter.default
nc.addObserver(self,
selector: #selector(handleInterruption),
name: AVAudioSession.interruptionNotification,
object: nil)
}

@objc func handleInterruption(notification: Notification) {
// To be implemented.
}


Related Topics



Leave a reply



Submit