Now what is happening is it is also controlling other music players. If i have a default music player after starting that if i start playing using my music player and then i press play/pause button in headset it controls default music player.
i have implemented a heaset broadcastreceiver like this,
switch (keyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_HEADSETHOOK:
Log.d("TAG", "TAG: KEYCODE_HEADSETHOOK");
if (MusicService.isPlaying()) {
MusicService.player.pause();
} else {
MusicService.player.start();
}
new MusicService().showNotification();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
Log.d("TAG", "TAG: KEYCODE_MEDIA_PLAY");
if (MusicService.isPlaying()) {
MusicService.player.pause();
} else {
MusicService.player.start();
}
new MusicService().showNotification();
break;
case KeyEvent.KEYCODE_MEDIA_PLAY:
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
Log.d("TAG", "TAG: KEYCODE_MEDIA_PAUSE");
break;
case KeyEvent.KEYCODE_MEDIA_STOP:
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
Log.d("TAG", "TAG: KEYCODE_MEDIA_NEXT");
if (MusicService.player.isPlaying()) {
MusicService.player.stop();
}
if (MusicService.songPosn < (MusicService.song.size() - 1)) {
MusicService.songPosn = MusicService.songPosn + 1;
if (SingleInstance.getInstance().getIndexCount()>= 1)
SingleInstance.getInstance().setIndexCount(SingleInstance.getInstance().getIndexCount()-1);
} else {
// play first song
MusicService.songPosn = 0;
}
new MusicService().playSong(true);
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
Log.d("TAG", "TAG: KEYCODE_MEDIA_PREVIOUS");
if (MusicService.player.isPlaying()) {
MusicService.player.stop();
}
if (MusicService.songPosn > 0) {
MusicService.songPosn = MusicService.songPosn - 1;
} else {
// play last song
MusicService.songPosn = MusicService.song.size() - 1;
}
new MusicService().playSong(true);
break;
}
If you are trying to get the hedsethook event in a activity follow the below code :
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HEADSETHOOK:
// Headset key detected
// Do your stuff here
return true;// To let the os know that the event is consumed here
}
}
return super.dispatchKeyEvent(event);
}
Make sure to returt true to consume the event .To get it done in a service use BroadCast receiver as follows:
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);//"android.intent.action.MEDIA_BUTTON"
MediaButtonIntentReceiver r = new MediaButtonIntentReceiver();
filter.setPriority(1000); //Sets receiver priority
registerReceiver(r, filter);
Related
int result = audioManager.requestAudioFocus(focusChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
startMediaPlayer(songPath);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioManager.registerAudioPlaybackCallback(new AudioManager.AudioPlaybackCallback() {
#Override
public void onPlaybackConfigChanged(List<AudioPlaybackConfiguration> configs) {
super.onPlaybackConfigChanged(configs);
boolean isFoundPlayOtherMusic = false;
if (configs.size() > 1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (configs != null) {
for (int i = 0; i < configs.size(); i++) {
if (configs.get(i).getAudioAttributes().getUsage() == USAGE_MEDIA && (configs.get(i).getAudioAttributes().getContentType() == CONTENT_TYPE_MUSIC || configs.get(i).getAudioAttributes().getContentType() == CONTENT_TYPE_UNKNOWN)) {
isFoundPlayOtherMusic = true;
}
}
if (isFoundPlayOtherMusic) {
controls.pauseControl(getApplicationContext());
} else {
if (audioFocus == AudioManager.AUDIOFOCUS_LOSS ||
audioFocus == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
audioFocus == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
controls.playControl(getApplicationContext());
}
}
}
} else {
controls.pauseControl(getApplicationContext());
}
} else if (configs.size() == 0) {
if (audioFocus == AudioManager.AUDIOFOCUS_LOSS ||
audioFocus == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
audioFocus == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)
controls.playControl(getApplicationContext());
}
}
}, handler);
}
here is the code that check the audio focus of audio manager, is audio manager gain to success focus then play the Music Player, I also implement the audioChangeFocusListener as below code.
private AudioManager.OnAudioFocusChangeListener focusChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
System.out.println("===== AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK : " + focusChange);
break;
case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
System.out.println("===== AUDIOFOCUS_GAIN_TRANSIENT : " + focusChange);
break;
case AudioManager.AUDIOFOCUS_GAIN:
System.out.println("===== AUDIOFOCUS_GAIN : " + focusChange);
if (!mp.isPlaying())
controls.playControl(getApplicationContext());
break;
case AudioManager.AUDIOFOCUS_LOSS:
System.out.println("===== AUDIOFOCUS_LOSS : " + focusChange);
if (mp.isPlaying())
controls.pauseControl(getApplicationContext());
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
System.out.println("===== AUDIOFOCUS_LOSS_TRANSIENT : " + focusChange);
if (mp.isPlaying())
controls.pauseControl(getApplicationContext());
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
System.out.println("===== AUDIOFOCUS_LOSS : " + focusChange);
}
}
};
Audio Focus is not working in android 9 and 10 both. I am using audio play with notification in my app.
Audio Focus not Gain and Loss in Our app, is it possible to stop our app music when audio play from other app, and when I play audio in my app then stop other music player from other app, is it possible then how?
This is also a sore subject for me. Try adding play dummy audio
https://stackoverflow.com/a/50678833
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioTrack audioTrack = new AudioTrack(
new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build(),
new AudioFormat.Builder()
.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
.setSampleRate(48000)
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.build(),
AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT),
AudioTrack.MODE_STREAM,
AudioManager.AUDIO_SESSION_ID_GENERATE
);
audioTrack.play();
audioTrack.stop();
audioTrack.release();
}
I am using the twilio for making the call and receiving the call. I am receiving the incoming call by using intent in onResum() method.How to get incoming number by using intent on connection.Also I want display customise popup when mobile screen will be lock.
This is my code for receiving call.
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
if (intent != null) {
/*
* Determine if the receiving Intent has an extra for the incoming connection. If so,
* remove it from the Intent to prevent handling it again next time the Activity is resumed
*/
Device device = intent.getParcelableExtra(Device.EXTRA_DEVICE);
Connection incomingConnection = intent.getParcelableExtra(Device.EXTRA_CONNECTION);
// Intent broadcast = new Intent(this, PhoneStateReceiver.class);
// NewVoiceCallFragment client = new NewVoiceCallFragment(incomingConnection);
// Intent intent1 = new Intent(this, CallDetectService.class);
String incoming_number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (incomingConnection == null && device == null) {
return;
}
intent.removeExtra(Device.EXTRA_DEVICE);
intent.removeExtra(Device.EXTRA_CONNECTION);
pendingConnection = incomingConnection;
pendingConnection.setConnectionListener(this);
mobjSessionManager.setKeyIncomingCollsid(pendingConnection.getParameters().get(incomingConnection.IncomingParameterCallSIDKey));
String incomingRecipientCallSid = pendingConnection.getParameters().get(incomingConnection.IncomingParameterCallSIDKey);
String incomingRecipientCallNumber = pendingConnection.getParameters().get(incomingConnection.IncomingParameterFromKey);
if (incomingRecipientCallNumber.equals(mobjSessionManager.getKeyCallerid())) {
tManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (isDisplayDilog) {
switch (getRingingMode())
{
case 1:
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
break;
case 2:
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
break;
case 3:
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
break;
}
// audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
// AsyninvokeIncomingNumber ser=new AsyninvokeIncomingNumber();
// ser.execute();
// Device.State str=device.getState();
unlockScreen();
showIncomingDialog();
}
}
}
}
//for ring :
private int getRingingMode()
{
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
return 1;
// break;
case AudioManager.RINGER_MODE_VIBRATE:
return 2;
// break;
case AudioManager.RINGER_MODE_NORMAL:
return 3;
// break;
}
return 0;
}
// for unlock screen
private void unlockScreen() {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
Currently I have a list of TextViews whose background get changed when click for the first time. But I also want when user clicks on the second time its background should again change and vice versa.
With my existing code I am only able to change background for the first click, when I am clicking it again its background is not changing.
Here is my code:
public void onClick(View v) {
switch (v.getId()) {
case R.id.goalText1:
if (count <= 2) {
goals.add(mGoal1.getText().toString());
mGoal1.setTextColor(getResources().getColor(R.color.black));
mGoal1.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText2:
if (count <= 2) {
goals.add(mGoal2.getText().toString());
mGoal2.setTextColor(getResources().getColor(R.color.black));
mGoal2.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText3:
if (count <= 2) {
goals.add(mGoal3.getText().toString());
mGoal3.setTextColor(getResources().getColor(R.color.black));
mGoal3.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText4:
if (count <= 2) {
goals.add(mGoal4.getText().toString());
mGoal4.setTextColor(getResources().getColor(R.color.black));
mGoal4.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText5:
if (count <= 2) {
goals.add(mGoal5.getText().toString());
mGoal5.setTextColor(getResources().getColor(R.color.black));
mGoal5.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText6:
if (count <= 2) {
goals.add(mGoal6.getText().toString());
mGoal6.setTextColor(getResources().getColor(R.color.black));
mGoal6.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.goalText7:
if (count <= 2) {
goals.add(mGoal7.getText().toString());
mGoal7.setTextColor(getResources().getColor(R.color.black));
mGoal7.setBackgroundColor(getResources().getColor(R.color.white));
count++;
} else {
Toast.makeText(SelectGoal.this, "cant select more", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnGoal:
Intent intent = new Intent(this, fiteness_level_selection.class);
try {
obj.put("SelectedGoal", goals);
} catch (Exception e) {
e.printStackTrace();
}
intent.putExtra("GoalJson", obj.toString());
startActivity(intent);
break;
}
So can anybody suggest me any easy way to achieve it.
Set a boolean array in your activity.
//suppose you've 3 textviews within listview
public boolean isTransparent[] = {false,false,false};
And then do this in your onClick method.
public void onOnclick(View v){
switch (v.getId()) {
//foreach textview do this
case R.id.textView1 :
int color;
if (isTransparent[0])
color = getResources().getColor(android.R.color.transparent);
else
color = getResources().getColor(R.color.white);
isTransparent[0]=!isTransparent[0];
textview1.setBackgroundColor(color);
break;
case R.id.textView2:
// now check for isTransparent[1]
and so on ...
...
}
}
As What I am understand is you want Change background for that you have take bool variable and in Button click you have to check the bool value.
Boolean click_firsttime = false;
Inside your Button click
use this way
If(click_firsttime == false){
//perform task
// and set bool value to true
click_firsttime = true;
}else{
// perform task and set bool value
click_firsttime = false;
}
First create a boolean :
private boolean foo = true;
Then change your code like this :
public void onClick(View v) {
switch (v.getId()) {
case R.id.goalText1:
if (foo) {
goals.add(mGoal1.getText().toString());
mGoal1.setTextColor(getResources().getColor(R.color.black));
mGoal1.setBackgroundColor(getResources().getColor(R.color.white));
count++;
foo = false;
} else {
// set background to another color
foo = true;
}
break;
I have an image button which has a click and a long click hooked up to it. On a long-press I display a custom vertical seek bar. All the functionality I need is fully functional with the exception of one requirement. I need to be able to start a swipe-up gesture after long pressing the button without lifting my finger. The slide gesture should operate on my vertical seek bar. I can already do this but I need to lift my finger after long pressing the button. Here's what I have so far
public class MainActivity : Activity
{
private ImageButton m_jump1;
private VerticalSeekBar m_seekUp;
private TextView m_progress;
private string[] m_values;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
m_values = new[] { "-5 Sec", "-15 Sec", "-1 Min", "-5 Min", "-15 Min", "-30 Min", "-1 H", "-6 H" };
m_seekUp = FindViewById<VerticalSeekBar>(Resource.Id.SliderUp);
m_seekUp.ProgressChanged += OnProgressChanged;
m_seekUp.Touch += OnTouch;
m_jump1 = FindViewById<ImageButton>(Resource.Id.Jump1);
m_jump1.Click += OnJump;
m_jump1.LongClick += OnShowSliderUp;
m_progress = FindViewById<TextView>(Resource.Id.ProgressTextView);
m_progress.Text = m_values[m_seekUp.Progress];
}
public override bool OnTouchEvent(MotionEvent e)
{
if (e.Action == MotionEventActions.Down)
{
if (m_seekUp.Visibility == ViewStates.Visible)
{
var rect = new Rect(m_seekUp.Left, m_seekUp.Top, m_seekUp.Right, m_seekUp.Bottom);
if (!rect.Contains((int)e.RawX, (int)e.RawY))
{
m_seekUp.Progress = 1;
m_seekUp.Visibility = ViewStates.Invisible;
m_progress.Visibility = ViewStates.Invisible;
}
}
}
return base.OnTouchEvent(e);
}
private void OnJump(object sender, EventArgs args)
{
if (m_seekUp.Visibility == ViewStates.Visible)
{
m_seekUp.Visibility = ViewStates.Invisible;
m_progress.Visibility = ViewStates.Invisible;
}
}
private void OnShowSliderUp(object sender, EventArgs args)
{
if (m_seekUp.Visibility == ViewStates.Invisible)
{
m_seekUp.Visibility = ViewStates.Visible;
m_progress.Visibility = ViewStates.Visible;
}
}
private void OnTouch(object sender, View.TouchEventArgs e)
{
switch (e.Event.Action)
{
case MotionEventActions.Up:
m_seekUp.Progress = 1;
m_seekUp.Visibility = ViewStates.Invisible;
m_progress.Visibility = ViewStates.Invisible;
break;
case MotionEventActions.Move:
e.Handled = false;
break;
case MotionEventActions.Down:
e.Handled = false;
break;
}
}
private void OnProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e)
{
switch (e.Progress)
{
case 0:
m_progress.Text = m_values[e.Progress];
break;
case 1:
m_progress.Text = m_values[e.Progress];
break;
case 2:
m_progress.Text = m_values[e.Progress];
break;
case 3:
m_progress.Text = m_values[e.Progress];
break;
case 4:
m_progress.Text = m_values[e.Progress];
break;
case 5:
m_progress.Text = m_values[e.Progress];
break;
case 6:
m_progress.Text = m_values[e.Progress];
break;
case 7:
m_progress.Text = m_values[e.Progress];
break;
}
}
}
I am working with Xamarin but any answers in Java will work too, I will convert the code myself
I am trying to implement the volume slider while casting and show the cast icon in the slider like in the Youtube app : http://imgur.com/kVxoKbM.
As of now I have overridden the dispatchKeyEvent function my activity, as explained in the cast developers documentation (shown in the code snipped below), which allows me to control the volume of the connected Chromecast perfectly. But on the device, it doesn't even show a slider at all.
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
if (mApiClient != null) {
double currentVolume = Cast.CastApi.getVolume(mApiClient);
if (currentVolume < 1.0) {
try {
Cast.CastApi.setVolume(mApiClient,
Math.min(currentVolume + VOLUME_INCREMENT, 1.0));
} catch (Exception e) {
Log.e(TAG, "unable to set volume", e);
}
}
} else {
Log.e(TAG, "dispatchKeyEvent - volume up");
}
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
if (mApiClient != null) {
double currentVolume = Cast.CastApi.getVolume(mApiClient);
if (currentVolume > 0.0) {
try {
Cast.CastApi.setVolume(mApiClient,
Math.max(currentVolume - VOLUME_INCREMENT, 0.0));
} catch (Exception e) {
Log.e(TAG, "unable to set volume", e);
}
}
} else {
Log.e(TAG, "dispatchKeyEvent - volume down");
}
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
I am not using the remoteMediaPlayer. So how can I implement a volume slider while controlling the connected Chromecast volume?