-
-
Save sabiou/b08e23e1ba4f24839c0ecf9cf1f013ae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.be.homsi.adapter; | |
import android.Manifest; | |
import android.content.BroadcastReceiver; | |
import android.content.ComponentName; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.IntentFilter; | |
import android.content.ServiceConnection; | |
import android.content.SharedPreferences; | |
import android.content.res.AssetFileDescriptor; | |
import android.media.MediaPlayer; | |
import android.os.AsyncTask; | |
import android.os.Bundle; | |
import android.os.Environment; | |
import android.os.IBinder; | |
import android.provider.MediaStore; | |
import android.support.v4.content.ContextCompat; | |
import android.support.v7.widget.RecyclerView; | |
import android.util.Log; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.Button; | |
import android.widget.ProgressBar; | |
import android.widget.SeekBar; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import com.be.homsi.R; | |
import com.be.homsi.app.AppConfig; | |
import com.be.homsi.controller.UserController; | |
import com.be.homsi.model.InterpretationModel; | |
import com.be.homsi.realm.RealmController; | |
import com.be.homsi.service.MediaPlayerService; | |
import com.be.homsi.service.NotificationGenerator; | |
import com.be.homsi.view.MainActivity; | |
import java.io.BufferedInputStream; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import java.util.List; | |
import java.util.PropertyResourceBundle; | |
import static android.Manifest.permission_group.STORAGE; | |
import static com.be.homsi.service.MediaPlayerService.Broadcast_BTN_PLAY; | |
public class AudioAdapter extends RecyclerView.Adapter<AudioAdapter.MyViewHolder> { | |
private List<InterpretationModel> passagList; | |
UserController user; | |
Context context; | |
RealmController realms; | |
MediaPlayer mediaPlayer; | |
Boolean wasPlaying = false; | |
String path; | |
private MediaPlayerService player; | |
boolean serviceBound = false; | |
public static final String Broadcast_PLAY_NEW_AUDIO = "com.be.homsi.PlayNewAudio"; | |
TextView tailles, durees; | |
SeekBar progres; | |
class MyViewHolder extends RecyclerView.ViewHolder { | |
TextView taille, duree, seekbarhint; | |
Button download, play, pause; | |
SeekBar progress; | |
MyViewHolder(View view) { | |
super(view); | |
taille = view.findViewById(R.id.textView10); | |
duree = view.findViewById(R.id.textView8); | |
download = view.findViewById(R.id.download); | |
pause = view.findViewById(R.id.pause); | |
play = view.findViewById(R.id.play); | |
seekbarhint = view.findViewById(R.id.textView13); | |
progress = view.findViewById(R.id.progressBar); | |
} | |
} | |
public AudioAdapter(Context context, List<InterpretationModel> passagList, Boolean serviceBound) { | |
this.passagList = passagList; | |
this.user = UserController.getInstance(); | |
this.realms = RealmController.getInstance(); | |
this.context = context; | |
this.serviceBound = serviceBound; | |
} | |
@Override | |
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { | |
View itemView = LayoutInflater.from(parent.getContext()) | |
.inflate(R.layout.item_audio, parent, false); | |
return new MyViewHolder(itemView); | |
} | |
@Override | |
public void onBindViewHolder(MyViewHolder holder, int position) { | |
InterpretationModel passag = passagList.get(position); | |
holder.taille.setText(passag.getTaille()); | |
holder.duree.setText(passag.getDuree()); | |
holder.download.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
//holder.download.setEnabled(false); | |
String url = AppConfig.URL_PREFIX + passag.getAudio(); | |
Log.d("download", url); | |
new DownloadFile(holder.progress, holder.download, holder.play, holder.pause, realms, passag).execute(url); | |
} | |
}); | |
mediaPlayer = new MediaPlayer(); | |
/*holder.progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { | |
@Override | |
public void onProgressChanged(SeekBar seekBar, int i, boolean b) { | |
int x = (int) Math.ceil(i / 1000f); | |
if (x < 10) { | |
holder.seekbarhint.setText("0:0" + x); | |
} else { | |
holder.seekbarhint.setText("0:" + x); | |
} | |
double percent = i / (double) seekBar.getMax(); | |
int offset = seekBar.getThumbOffset(); | |
int seekWidth = seekBar.getWidth(); | |
int val = (int) Math.round(percent * (seekWidth - 2 * offset)); | |
int labelWidth = holder.seekbarhint.getWidth(); | |
holder.seekbarhint.setX(offset + seekBar.getX() + val | |
- Math.round(percent * offset) | |
- Math.round(percent * labelWidth / 2)); | |
if (i > 0 && mediaPlayer != null && !mediaPlayer.isPlaying()) { | |
clearMediaPlayer(); | |
seekBar.setProgress(0); | |
} | |
} | |
@Override | |
public void onStartTrackingTouch(SeekBar seekBar) { | |
} | |
@Override | |
public void onStopTrackingTouch(SeekBar seekBar) { | |
if (mediaPlayer != null && mediaPlayer.isPlaying()) { | |
mediaPlayer.seekTo(seekBar.getProgress()); | |
} | |
} | |
});*/ | |
/*if(realms.getPathAudio(passag.getId()).equalsIgnoreCase("non")){ | |
holder.download.setVisibility(View.VISIBLE); | |
holder.play.setVisibility(View.GONE); | |
holder.pause.setVisibility(View.GONE); | |
}else{ | |
holder.download.setVisibility(View.GONE); | |
holder.play.setVisibility(View.VISIBLE); | |
holder.pause.setVisibility(View.GONE); | |
}*/ | |
holder.play.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
Log.d("playaudio", realms.getPathAudio(passag.getId())); | |
Log.d("playaudios", String.valueOf(passag.getId())); | |
progres = holder.progress; | |
durees = holder.duree; | |
tailles = holder.taille; | |
playAudio(realms.getPathAudio(passag.getId())); | |
} | |
}); | |
holder.pause.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
holder.play.setVisibility(View.VISIBLE); | |
holder.pause.setVisibility(View.GONE); | |
mediaPlayer.pause(); | |
} | |
}); | |
} | |
@Override | |
public int getItemCount() { | |
return passagList.size(); | |
} | |
private void clearMediaPlayer() { | |
mediaPlayer.stop(); | |
mediaPlayer.release(); | |
mediaPlayer = null; | |
} | |
private class DownloadFile extends AsyncTask<String, String, String> { | |
private String fileName; | |
private String folder; | |
InterpretationModel passag; | |
private RealmController realms; | |
private SeekBar progressBar; | |
private boolean isDownloaded; | |
Button download, play, pause; | |
/** | |
* Before starting background thread | |
* Show Progress Bar Dialog | |
*/ | |
DownloadFile(SeekBar progressBar, Button download, Button play, Button pause, RealmController realms, InterpretationModel passag) { | |
this.progressBar = progressBar; | |
this.passag = passag; | |
this.realms = realms; | |
this.download = download; | |
this.play = play; | |
this.pause = pause; | |
} | |
@Override | |
protected void onPreExecute() { | |
super.onPreExecute(); | |
} | |
/** | |
* Downloading file in background thread | |
*/ | |
@Override | |
protected String doInBackground(String... f_url) { | |
int count; | |
try { | |
URL url = new URL(f_url[0]); | |
URLConnection connection = url.openConnection(); | |
connection.connect(); | |
// getting file length | |
int lengthOfFile = connection.getContentLength(); | |
// input stream to read file - with 8k buffer | |
InputStream input = new BufferedInputStream(url.openStream(), 8192); | |
String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()); | |
//Extract file name from URL | |
fileName = f_url[0].substring(f_url[0].lastIndexOf('/') + 1, f_url[0].length()); | |
//Append timestamp to file name | |
fileName = timestamp + "_" + fileName; | |
//External directory path to save file | |
folder = Environment.getExternalStorageDirectory() + File.separator + "Homsi/"; | |
//Create androiddeft folder if it does not exist | |
File directory = new File(folder); | |
if (!directory.exists()) { | |
directory.mkdirs(); | |
} | |
// Output stream to write file | |
OutputStream output = new FileOutputStream(folder + fileName); | |
byte data[] = new byte[1024]; | |
long total = 0; | |
while ((count = input.read(data)) != -1) { | |
total += count; | |
// publishing the progress.... | |
// After this onProgressUpdate will be called | |
publishProgress("" + (int) ((total * 100) / lengthOfFile)); | |
Log.d("TAG", "Progress: " + (int) ((total * 100) / lengthOfFile)); | |
// writing data to file | |
output.write(data, 0, count); | |
} | |
// flushing output | |
output.flush(); | |
// closing streams | |
output.close(); | |
input.close(); | |
path = folder + fileName; | |
//play.setVisibility(View.VISIBLE); | |
//download.setVisibility(View.GONE); | |
//pause.setVisibility(View.GONE); | |
return "Downloaded at: " + folder + fileName; | |
} catch (Exception e) { | |
Log.e("Error: ", e.getMessage()); | |
} | |
//download.setEnabled(true); | |
return "Something went wrong"; | |
} | |
/** | |
* Updating progress bar | |
*/ | |
protected void onProgressUpdate(String... progress) { | |
// setting progress percentage | |
progressBar.setProgress(Integer.parseInt(progress[0])); | |
} | |
@Override | |
protected void onPostExecute(String message) { | |
// dismiss the dialog after the file was downloaded | |
progressBar.setProgress(0); | |
realms.UpdateInterpretationDownload(passag.getId(), folder + fileName); | |
Log.e("pathsid", String.valueOf(passag.getId())); | |
// Display File path after downloading | |
Toast.makeText(context, | |
message, Toast.LENGTH_LONG).show(); | |
} | |
} | |
public void playSong(SeekBar seekBar, String path) { | |
try { | |
if (mediaPlayer != null && mediaPlayer.isPlaying()) { | |
clearMediaPlayer(); | |
seekBar.setProgress(0); | |
wasPlaying = true; | |
} | |
if (!wasPlaying) { | |
if (mediaPlayer == null) { | |
mediaPlayer = new MediaPlayer(); | |
} | |
mediaPlayer.setDataSource(path); | |
mediaPlayer.prepare(); | |
mediaPlayer.setVolume(0.5f, 0.5f); | |
mediaPlayer.setLooping(false); | |
seekBar.setMax(mediaPlayer.getDuration()); | |
mediaPlayer.start(); | |
new Thread() { | |
@Override | |
public void run() { | |
int currentPosition = mediaPlayer.getCurrentPosition(); | |
int total = mediaPlayer.getDuration(); | |
while (mediaPlayer != null && mediaPlayer.isPlaying() && currentPosition < total) { | |
try { | |
Thread.sleep(1000); | |
currentPosition = mediaPlayer.getCurrentPosition(); | |
} catch (InterruptedException e) { | |
return; | |
} catch (Exception e) { | |
return; | |
} | |
seekBar.setProgress(currentPosition); | |
} | |
} | |
}.start(); | |
} | |
wasPlaying = false; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
public static class PlayReceivers extends BroadcastReceiver { | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
//mediaPlayer.pause(); | |
Log.d("playbutton", "ca mmarche"); | |
} | |
} | |
private void playAudio(String media) { | |
//Check is service is active | |
if (!serviceBound) { | |
Intent playerIntent = new Intent(context, MediaPlayerService.class); | |
playerIntent.putExtra("media", media); | |
context.startService(playerIntent); | |
context.bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE); | |
} else { | |
//preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE); | |
// return preferences.getInt("audioIndex", -1);//return -1 if no data found | |
//Store the new audio to SharedPreferences | |
SharedPreferences preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE); | |
SharedPreferences.Editor editor = preferences.edit(); | |
editor.putString("newAudio", media); | |
editor.apply(); | |
//Service is active | |
//Send media with BroadcastReceiver | |
//Send a broadcast to the service -> PLAY_NEW_AUDIO | |
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO); | |
context.sendBroadcast(broadcastIntent); | |
} | |
} | |
//Binding this Client to the AudioPlayer Service | |
private ServiceConnection serviceConnection = new ServiceConnection() { | |
@Override | |
public void onServiceConnected(ComponentName name, IBinder service) { | |
// We've bound to LocalService, cast the IBinder and get LocalService instance | |
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service; | |
player = binder.getService(); | |
player.setUIControls(progres,tailles,durees); | |
serviceBound = true; | |
Toast.makeText(context, "Service Bound", Toast.LENGTH_SHORT).show(); | |
} | |
@Override | |
public void onServiceDisconnected(ComponentName name) { | |
serviceBound = false; | |
} | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment