I am playing audio files(MP3) by clicking on Item view, and the previous file stop automatically but the problem is that after tapping 3rd item of recyclerview the 1st one does not play sound on its click and the same problem happened on some other clicks of the list. I have added full Adapter class
public class RingToneAdapter extends RecyclerView.Adapter<RingToneAdapter.RingToneViewHolder> {
//removed declared varaible for the sake of post to edit
static final int[] resID = {R.raw.a48, R.raw.funny_hen};
public RingToneAdapter(Context rcntx, List<RingTone_Items> ringtonelist) {
this.rcntx = rcntx;
this.ringtonelist = ringtonelist;
}
#NonNull
#Override
public RingToneViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
view = LayoutInflater.from(rcntx).inflate(R.layout.ringtone_values, viewGroup, false);
RingToneViewHolder ringToneViewHolder = new RingToneViewHolder(view);
return ringToneViewHolder;
}
//playing sounds on recycler view
#Override
public void onBindViewHolder(#NonNull final RingToneViewHolder ringToneViewHolder, final int i) {
final RingTone_Items ringTone_items = ringtonelist.get(i);
ringToneViewHolder.rtv.setText(ringTone_items.getRintonetv());
if (mSelectedItem == i) {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
mSelectedItem = -1;
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged();
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
if (oldpossssssss == i) {
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
}
});
}
#Override
public int getItemCount() {
return ringtonelist.size();
}
class RingToneViewHolder extends RecyclerView.ViewHolder {
private TextView rtv, hello, close;
private ImageView iconplay;
public RingToneViewHolder(#NonNull View itemView) {
super(itemView);
rtv = itemView.findViewById(R.id.ringtitle);
iconplay = itemView.findViewById(R.id.playicon);
}
}
How can I manage this smoothly according to click the play media file accordingly. Where is I am doing wrong please help me Thanks.
I would suggest you to use singletone media player in your viewHolders. Firstly, using multiple prepared mediaPlayers are not very memory efficient. Secondly, it will allow you to resolve problems with played sound on the background because one mediaPlayer will play only one audio at a time.
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged();
if (oldpossssssss == i) {
if(mp != null){
if(mp.mp.isPlaying()){
mp.pause();
} else{
mp.start();
}
}
} else {
createMediaPlayer(i)
}
}
});
Use this method when you create MediaPlayer
private void createMediaPlayer(int i)
{
if (mp!=null)
{
if(mp.isPlaying())
{
mp.stop();
mp.reset();
mp.release();
mp=null;
}
}
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
May be its work.
Related
I have chat app where user can share audio files. In recyclerview adapter i need to change icon of play button in following case:
Normally click on single item play button change into pause then into play again by clicking and on complete (Working fine)
Playing second audio file in recyclerview. Playing/Pause working ok but onComplete not calling on second audio file.
Playing other audio file while first audio file is playing. It should turn current position play button icon into pause and last position play button into pause.- Not working
I tried to save last position at onClick and used setTag/getTag etc. But i am not able to change icon of my play/pause button on MediaPlayer states.
My Recyclerview Adapter Code:
public class ChatAdapter extends PagingDataAdapter<TbsData, RecyclerView.ViewHolder> {
//0 stop , 1 play, 2 pause, 3 released
private static int MediaPlayer_State = 0;
MediaPlayer mPlayer= new MediaPlayer();
int mediaPlayerPlayingPosition = -1;
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_chat_audio, parent, false);
return new ViewHolderAudio(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int pos) {
customItem wrapper = getItem(holder.getAbsoluteAdapterPosition());
ViewHolderAudio ViewHolderAudio = (ViewHolderAudio) holder;
if(ViewHolderAudio.voicePlaybutton.getTag == null){
ViewHolderAudio.voicePlaybutton.setTag("playButton");
}
if (mPlayer==null){
mPlayer = new MediaPlayer();
}
ViewHolderAudio.audioSeekbar.setProgress(0);
if (ViewHolderAudio.voicePlaybutton.getTag().equals("playButton")){
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
}else {
Glide.with(context)
.load(R.drawable.ic_pause_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
}
ViewHolderAudio.voicePlaybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayerPlayingPosition == -1){
mediaPlayerPlayingPosition = ViewHolderAudio.getAbsoluteAdapterPosition();
}
if (mPlayer.isPlaying()) {
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
mPlayer.pause();
mPlayer.reset();
} else {
if (MediaPlayer_State == 2) {
MediaPlayer_State = 1;
mPlayer.start();
ViewHolderAudio.visualizer.setPlayer(mPlayer.getAudioSessionId());
ViewHolderAudio.audioSeekbar.setMax(mPlayer.getDuration());
} else {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
mPlayer.setDataSource(context, Uri.parse(wrapper.getUSER_MESSAGE()));
} else {
mPlayer.setDataSource(wrapper.getUSER_MESSAGE());
}
mPlayer.prepare();
mPlayer.start();
MediaPlayer_State = 1;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Unable to play audio", Toast.LENGTH_SHORT).show();
}
}
Glide.with(context)
.load(R.drawable.ic_pause_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
}
}
});
mpOncomplete(mPlayer,ViewHolderAudio.voicePlaybutton,ViewHolderAudio.audioSeekbar);
/*mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "onCompletion: "+context);
ViewHolderAudio.audioSeekbar.setProgress(0);
mPlayer.reset();
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
MediaPlayer_State = 0;
}
});*/
mediaMetadataRetrieverVoice.release();
pausePlayer = new MediaPlayerPause() {
#Override
public void pausePlayer(int state) {
Log.d(TAG, "pausePlayer: Pause Media Player Interface "+state);
if (state == 2 && mPlayer.isPlaying()) {
mPlayer.pause();
MediaPlayer_State = 2;
} else if (state == 3) {
mPlayer.release();
mPlayer = null;
MediaPlayer_State = 3;
}
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
}
};
}
public class ViewHolderAudio extends RecyclerView.ViewHolder {
ImageView audioThumnail, voicePlaybutton;
TextView audioDuration, audioTimestamp,voiceTitle;
SeekBar audioSeekbar;
ImageView msgDeliveryStatus;
public ViewHolderAudio(#NonNull View itemView) {
super(itemView);
userImage = itemView.findViewById(R.id.userImage);
audioThumnail = itemView.findViewById(R.id.audioThumbImage);
voiceTitle = itemView.findViewById(R.id.voiceTitle);
voicePlaybutton = itemView.findViewById(R.id.voicePlayButton);
audioSeekbar = itemView.findViewById(R.id.seekBar);
}
}
private void mpOncomplete (final MediaPlayer mp,ImageView view,SeekBar bar){
Log.d(TAG, "mpOncomplete: Media Player ");
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
bar.setProgress(0);
mediaPlayer.stop();
mediaPlayer.reset();
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.error(R.drawable.ic_image_not_found).into(view);
MediaPlayer_State = 0;
}
});
}
private void changeIcon(int mediaPlayerPlayingPosition, ImageView voicePlaybutton) {
notifyItemChanged(mediaPlayerPlayingPosition);
}
}
I created an application which pairs a cellphone to a bluetooth module.
i tested this application with a 4.2 android cellphone and it worked quite well but in cellphones with android higher than 6 the device is not fidning anything when i press " Scan for new devices " button.
but when i go through my phone bluetooth itself, i can find the module i was looking for..
Bluetooth connection class :
public class BluetoothConnectionActivity extends AppCompatActivity {
private ProgressDialog mProgressDlg;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;
BluetoothDevice device ;
private MediaPlayer mediaplayer = null ;
private Button bluetoothOnOff;
private Button viewpairedDevices;
private Button scanfornewDevices;
private Button blue2;
ImageView unMute;
View view1;
View view2;
private Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetoothconnectionlayout);
bluetoothOnOff = (Button) findViewById(R.id.bluetoothOnOff);
viewpairedDevices = (Button) findViewById(R.id.viewpairedDevicesButton);
scanfornewDevices = (Button) findViewById(R.id.scanfornewDevicesButton);
blue2 = (Button) findViewById(R.id.bluetoothOnOff2);
view1 = findViewById(R.id.viewFader);
view2 = findViewById(R.id.viewFader2);
unMute = (ImageView) findViewById(R.id.settingStartupSecondary);
mediaplayer = MediaPlayer.create(getApplicationContext(),R.raw.sfxturnon);
Handler startup1 = new Handler();
startup1.postDelayed(new Runnable() {
#Override
public void run() {
view1.animate().alpha(1f).setDuration(500);
view2.animate().alpha(1f).setDuration(500);
}
},1000);
Handler startup2 = new Handler();
startup2.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(500);
viewpairedDevices.animate().alpha(1f).setDuration(500);
scanfornewDevices.animate().alpha(1f).setDuration(500);
unMute.animate().alpha(1f).setDuration(100);
}
},1000);
//
// settingBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//
//
// AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
// amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
//
//// settingBtn.setEnabled(false);
//// settingBtn.animate().alpha(0f);
//
// unMute.animate().alpha(1f);
// unMute.setEnabled(true);
//
//
// Toast.makeText(getApplicationContext(), " Application muted. ", Toast.LENGTH_SHORT).show();
//
//
// }
// });
Handler dawg = new Handler();
dawg.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(1500);
viewpairedDevices.animate().alpha(1f).setDuration(2500);
scanfornewDevices.animate().alpha(1f).setDuration(3000);
}
},500);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning, Please wait...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});}
if (mBluetoothAdapter.isEnabled()){
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
}else {
blue2.setText("Bluetooth is Off");
bluetoothOnOff.setText("Bluetooth is Off");
}
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
viewpairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
Toast toast = Toast.makeText(getApplicationContext()," No paired device found.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
scanfornewDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
bluetoothOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
blue2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onBackPressed() {
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(true);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(true);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showDisabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showUnsupported() {
Toast toast = Toast.makeText(getApplicationContext()," Bluetooth is not supported by this device.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
bluetoothOnOff.setEnabled(false);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
showEnabled();
final Handler handler5 = new Handler();
handler5.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(150f).setDuration(5000);
blue2.animate().translationY(150f).setDuration(5000);
bluetoothOnOff.animate().alpha(0f).setDuration(3000);
blue2.animate().alpha(1f).setDuration(3000);
}
}, 500);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
// Intent newIntent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
//
// newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
//
// startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
Toast toast = Toast.makeText(getApplicationContext()," Found device" + device.getName(), Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.optionmenu,menu);
return super.onCreateOptionsMenu(menu);
}
}
Device list Class :
public class DeviceList extends AppCompatActivity {
private ListView mListView;
private AdapterClassBluetooth mAdapterClassBluetooth;
private ArrayList<BluetoothDevice> mDeviceList;
private BluetoothDevice device ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapterClassBluetooth = new AdapterClassBluetooth(this);
mAdapterClassBluetooth.setData(mDeviceList);
mAdapterClassBluetooth.setListener(new AdapterClassBluetooth.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Pairing..." , Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapterClassBluetooth);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast toast = Toast.makeText(getApplicationContext()," Device are paired, please wait...", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
Handler delaying = new Handler();
delaying.postDelayed(new Runnable() {
#Override
public void run() {
Intent communicate = new Intent(DeviceList.this,Security.class);
startActivity(communicate);
finish();
}
},1500);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
Toast toast = Toast.makeText(getApplicationContext(),"Unpaired.", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
mAdapterClassBluetooth.notifyDataSetChanged();
}
}
};}
Adapter class :
public class AdapterClassBluetooth extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;
public AdapterClassBluetooth(){
}
public AdapterClassBluetooth(Context context) {
super();
mInflater = LayoutInflater.from(context);
}
public void setData(List<BluetoothDevice> data) {
mData = data;
}
public void setListener(OnPairButtonClickListener listener) {
mListener = listener;
}
public int getCount() {
return (mData == null) ? 0 : mData.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adapterlist, null);
holder = new ViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name);
holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address);
holder.pairBtn = (Button) convertView.findViewById(R.id.btn_pair);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mData.get(position);
holder.nameTv.setText(device.getName());
holder.addressTv.setText(device.getAddress());
holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
holder.pairBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onPairButtonClick(position);
}
}
});
return convertView;
}
static class ViewHolder {
TextView nameTv;
TextView addressTv;
TextView pairBtn;
}
public interface OnPairButtonClickListener {
public abstract void onPairButtonClick(int position);
}
}
in an article i studied about this issue and find out that with this code :
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
i can make the application to support phones with android more than 6 so i can discover all nearby devices and pair with them,
The issue is, i don't know where should i exactly use this code..
i would really appreciate if you could tell me where to use it within the codes i showed here.
or simply tell me how to overcome this problem with any other code you may know.
In your AndroidManifest.xml file add this:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Then, instead of calling registerReceiver call this function:
private tryRegisterReceiver() {
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Here, permission is not granted
// after calling requestPermissions, the result must be treated in onRequestPermissionResult
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1000); // 100 or other desired code
} else {
// Permission has already been granted
// continue registering your receiver
registerReceiver();
}
}
To treat the result of the permission request
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
// continue registering your receiver
registerReceiver();
} else {
// permission denied
// show a message or finish your activity
}
return;
}
// other 'case' for other permissions if needed
}
}
This question already has answers here:
Android Media player play the song x times [closed]
(2 answers)
Closed 3 years ago.
How can I make this simple music player musics repeat for example 5 times or to loop the music for 1, 2, or 3 hour.
This is my code of a simple music player with a music list:
public class Musica extends AppCompatActivity implements Runnable {
private Button pause;
private Button stop;
private SeekBar mseek;
private MediaPlayer mp;
private Thread soundThread;
private Button play;
//list
AdRequest adRequest;
private AdView adView;
ListView listm;
String[] itemname = {
"music 1",
"music 2",
"music 3",
"music 4",
"music 5",
"music 6",
"Lullaby 1",
"Lullaby 2",
"Lullaby 3",
"Lullaby 4",
"Lullaby 5",
};
Integer[] imgid = {
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
};
#Override
protected void onDestroy() {
super.onDestroy();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_musica);
getSupportActionBar().hide();
adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
adView.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int error) {
adView.setVisibility(View.GONE);
}
});
CustomListAdapterMusic adapter = new CustomListAdapterMusic(this, itemname, imgid);
listm = (ListView) findViewById(R.id.listmusic);
listm.setAdapter(adapter);
listm.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String Slecteditem = itemname[+position];
Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
if (position == 0) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.babyone);
mp.start();
}
if (position == 1) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.babytwo);
mp.start();
}
if (position == 2) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.water);
mp.start();
}
if (position == 3) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.ocean);
mp.start();
}
if (position == 4) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.rain);
mp.start();
}
if (position == 5) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.sm);
mp.start();
}
if (position == 6) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.classica);
mp.start();
}
if (position == 7) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.relax6);
mp.start();
}
if (position == 8) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.twinkle7);
mp.start();
}
if (position == 9) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.ninar11);
mp.start();
}
if (position == 10) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.lullaby9);
mp.start();
}
play = (Button) findViewById(R.id.bplay);
pause = (Button) findViewById(R.id.bpause);
stop = (Button) findViewById(R.id.bstop);
mseek = (SeekBar) findViewById(R.id.seekBar);
setupListeners();
soundThread = new Thread(Musica.this);
soundThread.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
private void setupListeners()
{
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View currentView) {
mp.stop();
}
});
mseek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void run() {
int currentPosition = 0;
int soundTotal = mp.getDuration();
mseek.setMax(soundTotal);
while (mp != null && currentPosition < soundTotal) {
try {
Thread.sleep(300);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException SoundException) {
return;
} catch (Exception otherException) {
return;
}
mseek.setProgress(currentPosition);
}
}
}
For part one, implement an setOnCompletionListener as already answered here: Android Media player play the song x times
For repeating for for 1 hour, change the counter with the timer implementation:
// get current time in milliseconds + 1 hour
long tRef = System.currentTimeMillis() + 1 * 60 * 60 * 1000L;
// set listener
mp.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// current time
long tNow = System.currentTimeMillis();
if (tNow < tEnd) {
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}});
To trigger the looping again, you just need to set the tRef to a new value.
Side note: If you need both functionalities at the same time, then combine them into one listener as you cannot have two listeners on the same media player at the same time.
Alternative solution would be to set mp.setLooping() and make a timer task to turn it off, but I would not recommend it here, as it might require some lifecycle management.
Timer timerObj = new Timer();
TimerTask timerTaskObj = new TimerTask() {
public void run() {
if (mp != null) {
mp.setLooping(false)
}
}
};
timer.schedule(timerTaskObj, 0, 1 * 60 * 60 * 1000L);
I'm new to Android programming. I followed a mediaplayer tutorial but I'm now trying to make it more advance, the only problem is thats not working as expected.
When the song is finished it should start playing the next song, but doesn't update my seekbar (only updates Max) and it makes my buttons crash my app. I tried many things but can't fix it myself. If i press the next button however (before music track ends) the buttons and seekbar work.
What I'm want is my seekbar to reset for the new song and go again, and i want my buttons to work after the onCompletion next song.
Here my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
btPlay = (ImageButton) findViewById(R.id.btPlay);
btNxt = (ImageButton) findViewById(R.id.btNxt);
btPv = (ImageButton) findViewById(R.id.btPv);
btPlay.setOnClickListener(this);
btNxt.setOnClickListener(this);
btPv.setOnClickListener(this);
sb = (SeekBar) findViewById(R.id.seekBar);
updateSeekBar = new Thread() {
#Override
public void run() {
int TotalDuration = mp.getDuration();
int currentPosition = 0;
while (currentPosition < TotalDuration) try {
sleep(500);
currentPosition = mp.getCurrentPosition();
sb.setProgress(currentPosition);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
if (mp != null) {
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songlist");
position = b.getInt("pos", 0);
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
mp.stop();
mp.reset();
position = (position + 1) % mySongs.size();
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
sb.setMax(mp.getDuration());
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btPlay:
if (mp.isPlaying()) {
mp.pause();
btPlay.setImageResource(R.drawable.play);
} else {
mp.start();
btPlay.setImageResource(R.drawable.pause);
}
break;
case R.id.btNxt:
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
position = (position + 1) % mySongs.size();
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
sb.setMax(mp.getDuration());
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.btPv:
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
position = (position - 1 < 0) ? mySongs.size() - 1 : position - 1;
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
sb.setMax(mp.getDuration());
}
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
}
Errors (in android Monitor):
java.lang.IllegalStateException
There is a play button(sound review), when I hit it plays, but when I hit several times, it plays multiply.
I wanted to stop this with other topic's codes, didn't help, any idea?
img_scream1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaControl.isPlaying()==true){
mediaControl.pause();
}
else
{
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
mediaControl.start();
}
}
});
Change your code to something like this:
boolean isPaused = true;
img_scream1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isPaused){
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
mediaControl.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
}
});
mediaControl.start();
isPaused = false;
}
else
{
mediaControl.pause();
isPaused = true;
}
}
});
Don't create the mediaControl instance every time(Which makes the song to load from begining). Instead, you can initialise mediaControl to null and create an instance of it when it is null
mediaControl =null;
img_scream1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
if (mediaControl == null) {
mediaControl = MediaPlayer.create(java_sounds_scary.this, R.raw.hooray);
}
if (mediaControl.isPlaying() == true) {
mediaControl.pause();
} else {
mediaControl.start();
}
}
});