I'm building a Android app that streams simple radio station.
EDIT: I added the OnCreate event and the init() function.
on create:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
play_or_pause();
}
the init() function:
public void init() {
mediaPlayer = new MediaPlayer();
stream_url = "http://the_radio_station.m3u8";
playing_now = false;
fb_error = "";
}
on created I'm calling the AsyncTask method:
play_or_pause();
the AsyncTask method:
public class play_or_pause_AsyncTask extends
AsyncTask<Boolean, Integer, String> {
#Override
protected String doInBackground(Boolean... params) {
// TODO Auto-generated method stub
if (!params[0]) {
fb_error = "";
try {
if (mediaPlayer.isLooping() || mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
fb_error = String.valueOf(mediaPlayer.isPlaying());
mediaPlayer.setDataSource(stream_url);
mediaPlayer.prepare();
mediaPlayer.start();
playing_now = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
fb_error += e.toString();
} catch (SecurityException e) {
// TODO Auto-generated catch block
fb_error += e.toString();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
fb_error += e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
fb_error += e.toString();
}
} else {
mediaPlayer.stop();
playing_now = false;
}
return fb_error;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(MainActivity.this, fb_error, Toast.LENGTH_LONG).show();
}
}
when I'm opening another Activity and coming back to the MainActivity(which making the stream) its starting to run the streaming again without stooping the old one.
I reed many posts here, the only suggestion was to use:
if ( mediaPlayer.isPlaying()) mediaPlayer.stop();
but it ain't helping (someone wrote that the mediaPlayer object is strange, you cant tell what is the objecct real status - Like if the .isPlaying() is true / false).
so what I can do in this situation?
try this way i use everytime
#Override
public void onStop() {
super.onStop();
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
Related
i use Permission in manifest.xml (CALL_PHONE,READ_PHONE_STATE,PROCESS_INCOMING_CALLS,MODIFY_PHONE_STATE) ,ITelephony.aids i show this code in a blog .
in ITelephony.aids i write
i want to disable all incoming call when the checkbox is checked . Code not return error but not work . i test it in android 6.0 . please help me
CheckBox blockAll_cb;//,blockcontacts_cb;
BroadcastReceiver CallBlocker;
TelephonyManager telephonyManager;
ITelephony telephonyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_call_controller);
initviews();
blockAll_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d("Error 8","Is Checked1");
// TODO Auto-generated method stub
CallBlocker =new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Error 8","Is checked2");
// TODO Auto-generated method stub
telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
//Java Reflections
Class c = null;
try {
c = Class.forName(telephonyManager.getClass().getName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("Error 1",""+e);
}
Method m = null;
try {
m = c.getDeclaredMethod("getITelephony");
} catch (SecurityException e) {
// TODO Auto-generated catch block
Log.d("Error 2",""+e);
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
Log.d("Error 3",""+e);
e.printStackTrace();
}
m.setAccessible(true);
try {
telephonyService = (ITelephony)m.invoke(telephonyManager);
} catch (IllegalArgumentException e) {
Log.d("Error 4",""+e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.d("Error 5",""+e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
Log.d("Error 6",""+e);
// TODO Auto-generated catch block
e.printStackTrace();
}
telephonyManager.listen(callBlockListener, PhoneStateListener.LISTEN_CALL_STATE);
}//onReceive()
PhoneStateListener callBlockListener = new PhoneStateListener()
{
public void onCallStateChanged(int state, String incomingNumber)
{
if(state==TelephonyManager.CALL_STATE_RINGING)
{
if(blockAll_cb.isChecked())
{
try {
telephonyService.endCall();
Log.d("Error End","EndCall");
} catch (RemoteException e) {
Log.d("Error 7",""+e);
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
};//BroadcastReceiver
IntentFilter filter= new IntentFilter("android.intent.action.PHONE_STATE");
registerReceiver(CallBlocker, filter);
}
});
}
public void initviews()
{
blockAll_cb=(CheckBox)findViewById(R.id.cbBlockAll);
//blockcontacts_cb=(CheckBox)findViewById(R.id.cbBlockContacts);
}
#Override
protected void onDestroy() {
Log.d("Error 8","Error 8");
// TODO Auto-generated method stub
super.onDestroy();
}
}
I am new in android programming. I have a problem in stopping mediaplayer when I click the button for stop. I think I have some problem with my code because my sounds are looping that's is why mp.stop(); is not working or probably because of the sleep? I am not sure. Is there anyone who can help me with these? Thanks in advance.
Here is my code for stop:
bb5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
if (mp.isPlaying()){
mp.stop();
}
} // END onClick()
});
Here is my code for playing the sound:
protected void managerOfSound() {
int size = tempq.size();
for (int i = 0; i < tempq.size(); i++) {
String u =tempq.get(i);
//WHOLE
if (u.equals("a4")){
mp = MediaPlayer.create(this, R.raw.a4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}
}else if (u.equals("b4")){
mp = MediaPlayer.create(this, R.raw.b4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}
}else if (u.equals("c4")){
mp = MediaPlayer.create(this, R.raw.c4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}
I try to do app which show elements. Each element should start showing when the before element was hidden. Each element is showing 2 seconds. I try a lot of way:
Android/java - How to do that loop wait to do action
And now I try with Asynctask. I find a way:
public class MainActivity extends Activity
{
ImageView image1,image2;
int id = 0;
AsyncTask.Status status;
TextView txt;
String status1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LongOperation task = new LongOperation();
status = task.getStatus();
status1 = String.valueOf(status);
txt = (TextView) findViewById(R.id.txt);
image1 = (ImageView)findViewById(R.id.image1);
image2 = (ImageView)findViewById(R.id.image2);
do{
new LongOperation().execute("");
id=id+1;
txt.setText(status1);
try
{
try
{
task.get(2500, TimeUnit.MILLISECONDS);
} catch (TimeoutException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}while(id<3);
}
private class LongOperation extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute()
{
image1.setVisibility(View.VISIBLE);
image2.setVisibility(View.VISIBLE);
txt.setText(status1);
}
#Override
protected String doInBackground(String... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.interrupted();
}
return null;
}
#Override
protected void onPostExecute(String result) {
txt.setText("Executed");
image1.setVisibility(View.GONE);
image2.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(Void... values) {}
}
(This is a example). App run and end after 7.5 sec (everything ok) but images aren't shown when I start. What should I do?
I think you are creating a deadlock situation with your threads. The main UI thread is blocking at the line task.get(), which in turn is preventing the AsyncTask from running properly; its onPreExecute method is posted onto the UI Thread, and the doInBackground doesn't run until onPreExecute completes.
i created audio activity with seekbar, it was played but i have problem when seekbar in progress there is cutting each 1 second in sound because i used (Thread.sleep).
i check another solution in Internet, all codes i checked were use same concept.
this is my code
public class PlaySounds extends Activity implements Runnable {
SeekBar seeksounds;
MediaPlayer mp;
Handler handler = new Handler();
int id;
public boolean isFileExists(String fileName) {
try {
File myFile = new File(fileName);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
return true;
} catch (Exception e) {
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playsounds);
seeksounds = (SeekBar) findViewById(R.id.seeksounds);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
String path = Environment.getExternalStorageDirectory().toString() + "/dowload/splash.mp3";
if (isFileExists(path)) {
mp = new MediaPlayer();
try {
mp.setDataSource(path);
mp.prepare();
mp.start();
int maxD = mp.getDuration();
int currentD = mp.getCurrentPosition();
seeksounds.setMax(maxD);
seeksounds.setProgress(currentD);
new Thread(this).start();
seeksounds.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar arg0, int progress,
boolean arg2) {
mp.seekTo(progress);
seeksounds.setProgress(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
mp.release();
}
#Override
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
seeksounds.setProgress(currentPosition);
} catch (Exception e) {
return;
}
}
}
}
Try to add mp = null; here
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
mp.release();
mp = null;
}
have the following code to run an mp3 podcast
public void playPodcast( final Uri data){
new Thread (new Runnable(){
public void run() {
if(!mediaPlayer.isPlaying()){
try {
mediaPlayer.setDataSource(getApplicationContext(), data);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
duracaoPodcast = mediaPlayer.getDuration();
mediaPlayer.start();
if(!(controlTimer >= 1)){
timer();
controlTimer++;
}
primarySeekBarProgressUpdater();
}
}
}).start();
}
and to close the User Intent have:
voltar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
mediaPlayer.stop();
}
});
the problem occurs when the User closes the intent that all the return button phones with android is because it does not:
finish();
mediaPlayer.stop();
makes only:
finish();
and so the audio is still playing, even if I go back to that intent the pause:
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
frame.setVisibility(View.INVISIBLE);
}
}
});
button does not work, and if I press the play he starts a new audio on top of that emptied playing,
any idea how to solve?
put mediaPlayer.stop(); in activity onStop() Method as far as i understood your question.