Thanks all.
I work with bluetooth low energy android. In service I want to check if bluetoothadapter is enable or not. If not,after every 1 minute i continue to check. If it is enable I break and do some thing.
I know how to check but I do not know how to loop and break.
Thanks
In your service you can create an AsyncTask, and inside create the loop:
private class Task extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... arg0)
{
while (true)
{
if()
{
//it's enabled
break;
}
else
{
//it's disabled
}
Thread.sleep(60000);//millisecond to wait
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}//end background
#Override
protected void onPostExecute(String result)
{
}
}
Related
I wrote the following method to know the reachable of url.
public boolean isMyURLReachable(String url){
boolean reachable = false;
try {
reachable = InetAddress.getByName(url).isReachable(2000);
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return reachable;
}
and I call it like that.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
boolean reachable = isMyURLReachable("www.google.com");
if(reachable)
Toast.makeText(getApplicationContext(), "Reachable", 500).show();
else
Toast.makeText(getApplicationContext(), "Unreachable", 500).show();
}
});
But android.os.NetworkMainThreadException occur, do I need anything to put in my androidmanifest.xml file or my idea is being wrong?
NetworkMainThreadException is thrown when an application attempts to perform a networking operation on its main thread.
Please try to perform that in an AysncTask or another thread.
Reference:
http://developer.android.com/reference/android/os/AsyncTask.html
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
I wrote the following inner class.
class URLCheckTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... url) {
boolean reachable = false;
try {
reachable = InetAddress.getByName(url[0]).isReachable(7000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(reachable)
return "1";
else
return "0";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("1"))
Toast.makeText(getApplicationContext(), "reachable", 500).show();
else
Toast.makeText(getApplicationContext(), "unreachable", 500).show();
}
}
and call it from onClick() method.
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new URLCheckTask().execute("www.google.com");
}
});
No exception occur this time. But...., the result is not correct even though I can call it from emulator's browser, it always show me unreachable.
Hi have a progressBar that i run. but when the user exits the app via the home button and then re-enters it by holding down the home button and selected the app. The progressBar setProgress flickers between an old value and a new one almost as if its remembering the previous state. I have created a function in my on pause/onResume methods to pause the timer save the values and on resume get those values and start the timer and progress bar again. The confusing thing is it works the onPause stuff works perfectly if the onPause function is run and the user stays in the app for example presses the back button. Does anyone know where im going wrong or how to correctly implement a progressBar using a CountDownTimer?
heres my code
#Override
protected void onResume() {
// TODO Auto-generated method stub
Log.v("Game","ONRESUME");
loadData();
layoutChecks();
loadViews();
try {
if(!myData.get("completed").equals("3")){
hintCheck();
getHints();
startTimer();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onResume();
}
#Override
protected void onPause() {
Log.v("Game","ONPAUSE");
try {
if(!myData.get("completed").equals("3")){
pauseTimer();
updateData();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPause();
}
public void loadViews(){
progressBar = new ProgressBar(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressD = progressBar.getProgressDrawable();
}
public void prepareProgressBar(){
progressD.setLevel(0);
progressBar.setProgress(0);
progressD.setLevel(points*100);
progressBar.setProgress(points);
}
public void startTimer(){
try {
points = Integer.valueOf(myData.getJSONObject("Data").getString("points"));
int timer = points;
hasTimerCancelled = false;
prepareProgressBar();
counter = new MyCount(timer/2 * 1000,1000);
counter.start();
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void pauseTimer(){
try {
counter.cancel();
hasTimerCancelled = true;
JSONObject Data = myData.getJSONObject("Data");
Data.put("points", String.valueOf(points));
myData.put("Data", Data);
updateData();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class MyCount extends CountDownTimer{
public long totaltime;
public MyCount(long totalTime, long countDownInterval) {
super(totalTime, countDownInterval);
totaltime = totalTime;
}
#Override
public void onFinish() {
counter.cancel();
points = 0;
progressBar.setProgress(0);
}
#Override
public void onTick(long millisUntilFinished) {
if(!hasTimerCancelled){
if(points > 0){
points = points - 1;
}
progressBar.setProgress((int) totaltime);
}
}
}
I am trying to run audios one after another with a time gap of 5 seconds. However I dont really see that happening. My third audio in the list is played and others are skipped. This means while debugging only music3 is being played and others are not. I would love alternate methods of doing this. Moreover I used prepare method just like that. Makes no difference while running though.
for(int j=0;j<3;j++)
{
if(j==0)
{
xnp = MediaPlayer.create(this,R.raw.ticktock);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
xnp.prepare();
xnp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 5000);
xnp.stop();
}
if(j==1)
{
xnp = MediaPlayer.create(this,R.raw.music2);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
xnp.prepare();
xnp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 5000);
xnp.stop();
}
else if (j==2)
{
xnp = MediaPlayer.create(this,R.raw.music3);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
xnp.prepare();
xnp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 5000);
xnp.stop();
intenter();
}
}
Your current implementation does not work because the media playback is not done on the main thread, so you are immediately playing all 3 media resources, so only the third one is heard.
I think you might want to call MediaPlayer#setOnCompletionListener on your MediaPlayer object. In the completion listener, you can then postDelayed onto your Handler to queue up the next resource to play.
I'm trying to develop an Android application which transfers images from one device to another. The received image would then be shown on the ImageView inside my application. To achieve my task, I thought to send a byte array of the bitmap. I'm able to get the first image on the imageview. But, as soon as I click on the button to send another image the application fails to send the bitmap. It shows me an exception "java.io.IOException: Service fiscovery failed." To send any image successfully I need to restart my application on the receiving/remote device. Can anyone please suggest a solution to mu problem. The logcat has also been included below.
Code to establish the connection:
private class StartConnectionThread extends Thread{
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public StartConnectionThread(BluetoothDevice device){
BluetoothSocket tempBluetoothSocket=null;
bluetoothDevice=device;
try
{
System.out.println(uuid);
tempBluetoothSocket=device.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException ioException)
{
}
bluetoothSocket=tempBluetoothSocket;
}
#Override
public void run() {
// TODO Auto-generated method stub
bluetoothAdapter.cancelDiscovery();
try
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bluetoothSocket.connect();
}
catch(IOException ioException)
{
System.out.println("bluetoothSocketInThread failed");
try
{
bluetoothSocket.close();
}
catch(IOException cancelIOException)
{
}
return;
}
manageConnectedSocket(bluetoothSocket);
}
public void cancel()
{
try
{
bluetoothSocket.close();
}
catch(IOException ioException)
{
}
}
}
Code to accept the connection:
private class AcceptConnectionThread extends Thread
{
private final BluetoothServerSocket bluetoothServerSocket;
public AcceptConnectionThread() {
// TODO Auto-generated constructor stub
System.out.println("constructor");
BluetoothServerSocket tempBluetoothServerSocket=null;
try
{
tempBluetoothServerSocket=bluetoothAdapter.listenUsingRfcommWithServiceRecord("My Souvenirs", uuid);
}
catch(IOException ioException)
{
}
bluetoothServerSocket=tempBluetoothServerSocket;
}
#Override
public void run() {
// TODO Auto-generated method stub
BluetoothSocket bluetoothSocket=null;
while(true)
{
try
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(bluetoothServerSocket);
if(bluetoothServerSocket!=null)
{
bluetoothSocket=bluetoothServerSocket.accept();
}
System.out.println("accept");
}
catch(IOException ioException){
break;
}
if(bluetoothSocket!=null)
{
manageConnectedSocket(bluetoothSocket);
try {
bluetoothServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
public void cancel()
{
try{
bluetoothServerSocket.close();
}
catch(IOException ioException){
}
}
}
Code to manage the connection:
private class ManageConnectedDevicesThread extends Thread
{
private final BluetoothSocket connectedBluetoothSocket;
public ManageConnectedDevicesThread(BluetoothSocket socket) {
// TODO Auto-generated constructor stub
connectedBluetoothSocket=socket;
InputStream tempInputStream=null;
OutputStream tempOutputStream=null;
try
{
tempInputStream=socket.getInputStream();
tempOutputStream=socket.getOutputStream();
}
catch(IOException ioException)
{
}
inputStream=tempInputStream;
outputStream=tempOutputStream;
}
#Override
public void run() {
// TODO Auto-generated method stub
byte[] buffer=new byte[1024*8];
int bytes;
while(true)
{
try
{
bytes=inputStream.read(buffer);
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
System.out.println("handler");
}
catch(IOException ioException)
{
System.out.println("for handler:" +ioException);
break;
}
}
}
public void write(byte[] bytes)
{
try
{
outputStream.write(bytes);
}
catch(IOException ioException){
System.out.println("exception in wrie tatement of managing connections");
}
}
public void close()
{
try {
connectedBluetoothSocket.close();
} catch (IOException e) {
// TODO: handle exception
}
}
}
Code to reset the connection:
void resetConnection()
{
if(inputStream!=null)
{
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(outputStream!=null)
{
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(startConnectionThread!=null)
{
System.out.println("start wala active tha");
startConnectionThread.cancel();
}
if(acceptConnectionThread!=null)
{
System.out.println("accept wala active tha");
acceptConnectionThread.cancel();
}
if(manageConnectedDevicesThread!=null)
{
System.out.println("manage wala active tha");
manageConnectedDevicesThread.close();
}
}
}
code for handler is shown below:
private final Handler handler=new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
System.out.println("MESSAGE_READ");
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
byte[] b=readMessage.getBytes();
Bitmap bitmap1=BitmapFactory.decodeByteArray(readBuf, 0, readBuf.length);
imageView.setImageBitmap(bitmap1);
break;
}
};
The logcat shows the following:
01-25 14:49:31.800: D/dalvikvm(9451): Debugger has detached; object registry had 1 entries
01-25 14:49:38.380: V/BluetoothSocket.cpp(9451): initSocketNative
01-25 14:49:38.380: V/BluetoothSocket.cpp(9451): ...fd 40 created (RFCOMM, lm = 26)
01-25 14:49:38.380: V/BluetoothSocket.cpp(9451): initSocketFromFdNative
01-25 14:49:40.420: D/BluetoothUtils(9451): isSocketAllowedBySecurityPolicy start : device null
01-25 14:49:41.680: I/System.out(9451): bluetoothSocketInThread failed
01-25 14:49:41.680: V/BluetoothSocket.cpp(9451): abortNative
01-25 14:49:41.680: V/BluetoothSocket.cpp(9451): ...asocket_abort(40) complete
01-25 14:49:41.680: V/BluetoothSocket.cpp(9451): destroyNative
01-25 14:49:41.680: V/BluetoothSocket.cpp(9451): ...asocket_destroy(40) complete
Thanks in advance.
Maybe you can try adding thread.sleep for a second? See this discussion:
"The only way I've been able to fix the problem is by adding a
thread.sleep for a second before closing the connection."
also see dan's two consecutive comments on this thread:
"I was able to get this to run only after separating the calls to
findBT(); openBT();
Otherwise, mmSocket.connect(); throws an exception, “Service discovery
failed”
but if I put findBT() in onCreate() and just use the button for
openBT(); it works fine.
Or, if I make a second button, one for each, it works fine.
Suggestions?"
the excerpts from the second comment:
Set pairedDevices = mBluetoothAdapter.getBondedDevices();
mmDevice = mBluetoothAdapter.getRemoteDevice(“00:06:66:46:5A:91″);
if (pairedDevices.contains(mmDevice))
{
statusText.setText(“Bluetooth Device Found, address: ” + mmDevice.getAddress() );
Log.d(“ArduinoBT”, “BT is paired”);
}
where I entered the address of my Bluetooth device. The original code
finds the device and returns the correct address, but
mmSocket.connect(); generates an exception “java.io.IOException:
Service discovery failed”
Suggestions?
I am trying to figure out how to have a progress bar that says "Loading. Please Wait..." while my media player prepares a streaming file. What occurs now is that it displays after the song is prepared. how can i fix this?
mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
/*dubstep stream*/
try {
dubstepMediaPlayer.setDataSource(dubstepPlaylistString[0]);
dubstepMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
dubstepMediaPlayer.prepare();
} 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();
}
dubstepMediaPlayer.start();
if(dubstepMediaPlayer.isPlaying()){
mediaPlayerLoadingBar.dismiss();
}`
EDIT:
This is the code I have now:
`switch(pSelection){
case 1:
new AsyncTask<Void, Void, Void>(){
#Override
protected void onPreExecute(){
mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
try {
dubstepMediaPlayer.setDataSource(dubstepPlaylistString[0]);
} catch (IllegalArgumentException 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();
}
dubstepMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
return null;
}
protected void onPostExecute(Void result){
//mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true)
dubstepMediaPlayer.prepareAsync();
dubstepMediaPlayer.start();
mediaPlayerLoadingBar.dismiss();
}
}.execute();`
If someone Still facing this problem here is the code below
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
if(translation.equals("NIV"))
{
if(AudioPlaying==false)
{
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(Main.this);
mediaController = new MediaController(Main.this);
}
else
mediaController.show();
}
else
Toast.makeText(getBaseContext(), "عفوا, جاري تحميل ملفات الصوت الخاصة بترجمة الفانديك ", Toast.LENGTH_LONG).show();
pd = new ProgressDialog(Main.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
//Thread.sleep(5000);
try
{
mediaPlayer.setDataSource(AudioUrlPath);
mediaPlayer.prepare();
mediaPlayer.start();
AudioPlaying=true;
}
catch (IOException e) {
Log.e("AudioFileError", "Could not open file " + AudioUrlPath + " for playback.", e);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
//b.setEnabled(true);
}
}
};
task.execute((Void[])null);
The issue lies in that you are not doing anything asynchronously here, and you should be. You should use an AsyncTask to do your work.
Take a look at 'the 4 steps', as detailed here:
The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
EDIT:
You can create an anonymous inner class to do your bidding, which may be similar to how you are creating your onClick handler. In your onClick do something like this:
//pseudo-code...
onClick(View v, ...) {
new AsyncTask<Generic1, Generic2, Generic3>() {
protected void onPreExecute() {
// do pre execute stuff...
}
protected Generic3 doInBackground(Generic1... params) {
// do background stuff...
}
protected void onPostExecute(Generic3 result) {
// do post execute stuff...
}
}.execute();
}
Don't forget to keep an eye on your generics here!
Here is the activity class.Here i am showing the way only.
package com.android.mediaactivity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class MediaActivity extends Activity
{
public LinearLayout mainLayout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainLayout=(LinearLayout)findViewById(R.id.mainlinear);
MediaPlayer media=new MediaPlayer(this);
media.startPlayer();
}
}
Here is mediaplayerclass.
package com.android.mediaactivity;
import java.io.IOException;
import android.media.MediaPlayer.OnPreparedListener;
public class MediaPlayer implements OnPreparedListener {
MediaActivity mediaActivity;
android.media.MediaPlayer mediaPlayer;
public MediaPlayer(MediaActivity mediaActivity) {
this.mediaActivity = mediaActivity;
}
public void startPlayer() {
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.reset();
try {
mediaPlayer.setDataSource("");
mediaPlayer.prepareAsync();
toggleProgress(true);
} catch (IllegalArgumentException 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(); } } public void onPrepared(android.media.MediaPlayer mp) { toggleProgress(false); mediaPlayer.start(); }
public void toggleProgress(final boolean show) {
mediaActivity.runOnUiThread(new Runnable() {
public void run() {
if (show) mediaActivity.mainLayout.setVisibility(mediaActivity.mainLayout.VISIBLE);
else mediaActivity.mainLayout.setVisibility(mediaActivity.mainLayout.INVISIBLE);
}
});
}
}
}
}
And here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/mainlinear"
android:visibility="invisible">
<ProgressBar android:id="#+id/ProgressBar01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>
When you say prepare on the underlying mediaplayer object, internally it really does some preparation like - setting up the extractor for the file, setting up the audio decoder to decode the encoded audio file and setting up the audio sink to play the raw audio data that was decoded from the decoder. Now all this will take time, it is not instantaneous.
So in your original code, you check if the mediaplayer isPlaying and then dismiss it but the problem is at that point of time the mediaplayer is not playing the audio yet and thus your dismiss is never called so it always visible.
What you need to do is implement the listener MediaPlayer.OnPreparedListener and when the method onPrepared is called in your application call the dismiss mediaPlayerLoadingBar.dismiss(); in that method.
Here is my solution :
The prepareAsync function used to prepare the audio and it is a non blocking operation (it is not blocking the main thread of the app).
Then I used the callback setOnPreparedListener to get notified when the
prepareAsync return, and the audio is ready
public void playAudio(String audioFile){
//init the progress dialog
final ProgressDialog progressDialog = new ProgressDialog(SubjectActivity.this);
try {
progressDialog.setCancelable(false);
progressDialog.setMessage(" Waiting to Prepare ...");
progressDialog.show();
// pass the url file to the media player
mediaplayer.setDataSource(audioFile);
mediaplayer.prepareAsync();
} 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();
}
//the callback gets called when prepareAsync audio file become ready,
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaplayer.start();
// cancel the dialog
progressDialog.cancel();
}
});
}
Finally found out:
Guys very Imp point:
After setting url
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
I have added prepare_sync() and added handler cause it was crashing for big files
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mediaPlayer.prepareAsync();
ProgressDialog progressDialog = ProgressDialog.show(Player.this,
"Loading Title", "Loading Message");
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
});
// might take long! (for buffering, etc)
mediaPlayer.start();
}
},500);
This code will add progressbar too.
Points:
set url
prepareasync
OnPreparedlistener
Progressbar
mp.start-done
This is my way of doing btw I have heard there is alternative Exoplayer have a look at that too !