music player play 2 song at the same time - android

i'm a beginner and i have some trouble with my android app. my app have 2 activities. the first is PlayerActivity.java it will list all song in sdcard by a listView and when i click on a item then the PlaysongActivity will appear.It's OK but when i press back button i'll show listview of song again but when i click on an item again then it open a new activity while the old one still playing. now i have 2 songs are playing at the same time. how can i solve this trouble? here is my code.
public class PlayerActivity extends Activity {
String pathToFile = new String("");
private List song = new ArrayList();
ListView listSong;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listSong = (ListView) findViewById(R.id.list);
listAllSong();
}
private void listAllSong() {
String end = ".mp3";
File myMp3Dir = new File("/sdcard/");
final File[] filelist = myMp3Dir.listFiles();
for (File f : filelist) {
if (!f.isDirectory()) {
if (f.getName().toLowerCase().contains(end)) {
song.add(f.getName());
}
}
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, song);
listSong.setAdapter(adapter);
listSong.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String path = parent.getItemAtPosition(position).toString();
Intent myIntent = new Intent(getApplicationContext(),
PlaysongActivity.class);
myIntent.putExtra("pathOfSong", path);
startActivity(myIntent);
finish();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.player, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
return rootView;
}
}
}
/and PlaysongActivity/
public class PlaysongActivity extends Activity {
MediaPlayer mp1;
SeekBar seekBar;
Boolean isPaused=false;
Handler mHandler=new Handler();
Boolean isMovingSeekBar=false;
ImageButton button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playsong);
TextView tvPlaysong=(TextView) findViewById(R.id.tv);
mp1=new MediaPlayer();
seekBar=(SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (isMovingSeekBar) {
mp1.seekTo(progress);
}
}
});
button=(ImageButton) findViewById(R.id.btnPlay);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mp1.isPlaying()) {
mp1.pause();
button.setImageResource(android.R.drawable.ic_media_play);
} else if (isPaused) {
mp1.start();
button.setImageResource(android.R.drawable.ic_media_pause);
}
}
});
Intent i=getIntent();
String path=i.getStringExtra("pathOfSong");
tvPlaysong.setText(path);
if(mp1.isPlaying()) mp1.stop();
playSong(path);
}
private void playSong(String path) {
seekBar.setProgress(0);
if(mp1!=null) mp1.stop();
try {
mp1.setDataSource("/sdcard/" + path);
mp1.prepare();
mp1.start();
seekBar.setMax(mp1.getDuration());
updateSeekBar();
isPaused = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
button.setImageResource(android.R.drawable.ic_media_pause);
}
private void updateSeekBar() {
mHandler.postDelayed(getTimeTask, 1000);
}
private Runnable getTimeTask=new Runnable() {
public void run() {
long duration=mp1.getDuration();
long currentPosition=mp1.getCurrentPosition();
seekBar.setProgress((int) currentPosition);
mHandler.postDelayed(this, 1000);
}
};
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.playsong, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_playsong,
container, false);
return rootView;
}
}
}

In PlaysongActivity, override onStop() and call release() on the MediaPlayer.
This will stop playback (and release resources) when you exit that activity.

Related

Error: ViewPostImeInputStage ACTION_DOWN

I can't figure out why my onClick method for my buttons are not working. Everytime I click the button, my logcat says ViewPostImeInputStage Action_Down.
I appreciate any help!
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
BluetoothConnect fragment = new BluetoothConnect();
transaction.add(R.id.sample_content_fragment, fragment);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
And this is my fragment.
public class BluetoothConnect extends Fragment {
//For debugging purposes
private static final String TAG = "BluetoothConnect";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
//Main buttons
private Button shareButton;
private Button listenButton;
private TextView test;
/**
* Name of the connected device
*/
private String mConnectedDeviceName = null;
/**
* Local Bluetooth adapter
*/
private BluetoothAdapter mBluetoothAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
listenButton = (Button) view.findViewById(R.id.listen);
shareButton = (Button) view.findViewById(R.id.share);
test = (TextView) view.findViewById(R.id.test);
}
#Override
public void onStart() {
super.onStart();
//If BT is not on, request that it be enabled
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
setupButtons();
}
}
#Override
public void onDestroy() {
super.onDestroy();
//Figure out what to do if we need to destroy
}
#Override public void onResume() {
super.onResume();
//figure out what to do if person pauses out of app
}
public void setupButtons() {
Log.d(TAG, "setupButtons()");
//Initialize the music buttons
listenButton.setOnClickListener(new ButtonOnClickListener("listen"));
Log.d(TAG, "finished listenButton");
shareButton.setOnClickListener(new ButtonOnClickListener("share"));
}
private class ButtonOnClickListener implements View.OnClickListener {
String type;
public ButtonOnClickListener(String button) {
Log.d(TAG, this.type);
this.type = button;
}
public void onClick(View view) {
if (this.type == "listen") {
listenMusic();
} else {
shareMusic();
}
}
}
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
private void listenMusic() {
Log.d(TAG, "OMG ITS WORKING");
}
private void shareMusic() {
Log.d(TAG, "OMG ITS WORKING");
}
}
Thanks so much!
have a look here
https://stackoverflow.com/a/32016362/5281187
Wrap your layout over the one you already have

Customising zbar scanner overlay

I am using the library barcodescanner from https://github.com/dm77/barcodescanner.
Currently the scanner displays a rectangle and a laser across the middle.
that looks similar to:
I am looking to make this view into a square since I am only scanning QR codes and to remove the laser and would appreciate some help.
My code that I have written so far for the scanner fragment is below
public class ScannerFragment extends Fragment implements
ZBarScannerView.ResultHandler
{
private static final String FLASH_STATE = "FLASH_STATE";
private static final String AUTO_FOCUS_STATE = "AUTO_FOCUS_STATE";
private static final String SELECTED_FORMATS = "SELECTED_FORMATS";
private static final String CAMERA_ID = "CAMERA_ID";
private ZBarScannerView mScannerView;
private boolean mFlash;
private boolean mAutoFocus;
private ArrayList<Integer> mSelectedIndices;
private int mCameraId = -1;
Communicator messenger;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
messenger=(Communicator) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
mScannerView = new ZBarScannerView(getActivity());
if (state != null) {
mFlash = state.getBoolean(FLASH_STATE, false);
mAutoFocus = state.getBoolean(AUTO_FOCUS_STATE, true);
mSelectedIndices = state.getIntegerArrayList(SELECTED_FORMATS);
mCameraId = state.getInt(CAMERA_ID, -1);
} else {
mFlash = false;
mAutoFocus = true;
mSelectedIndices = null;
mCameraId = -1;
}
setupFormats();
return mScannerView;
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuItem menuItem;
if (mFlash) {
menuItem = menu.add(Menu.NONE, R.id.menu_flash, 0, R.string.flash_on);
} else {
menuItem = menu.add(Menu.NONE, R.id.menu_flash, 0, R.string.flash_off);
}
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_ALWAYS);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.menu_flash:
mFlash = !mFlash;
if (mFlash) {
item.setTitle(R.string.flash_on);
} else {
item.setTitle(R.string.flash_off);
}
mScannerView.setFlash(mFlash);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(FLASH_STATE, mFlash);
outState.putBoolean(AUTO_FOCUS_STATE, mAutoFocus);
outState.putIntegerArrayList(SELECTED_FORMATS, mSelectedIndices);
outState.putInt(CAMERA_ID, mCameraId);
}
#Override
public void handleResult(Result rawResult) {
new Thread(new Runnable() {
#Override
public void run() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(), notification);
r.play();
}
catch (Exception e) {
}
}
}).start();
QRResults scanResult = QRResults.getInstance();
scanResult.Extract(rawResult.getContents());
if (scanResult.dataExtractedOK)
{
if (scanResult.canPerformElectricityComparison() || scanResult.canPerformGasComparison())
{
messenger.updateTextView("Found Code");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(getActivity(), SearchResult.class);
startActivity(i);
}
}, 2000);
}
}
else
{
messenger.updateTextView("Invalid Code");
// Restart Camera after 2 second delay
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mScannerView.startCamera();
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
messenger.updateTextView("Finding code...");
}
}, 2000);
}
}
public void onFormatsSaved(ArrayList<Integer> selectedIndices) {
mSelectedIndices = selectedIndices;
setupFormats();
}
public void setupFormats() {
List<BarcodeFormat> formats = new ArrayList<BarcodeFormat>();
formats.add(BarcodeFormat.QRCODE);
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
I think I need to extend a class from the library and override some of the methods in it but I'm not sure how to do this and have the overridden methods used in my scanner class.
Thank you for your time.
Add library module in a project (not as a dependency). Here is a tutorial how to add a library module in Android Studio.
Go to library module and find in ViewFinderView.java class drawLaser(Canvas canvas) method (draws the line in the middle).

Android - Mediaplayer Audio Streaming, rewind and forward

I have an android app that streams audio by URL (its an infinite stream) and it works. But I need to allow users to rewind X seconds and forward X seconds ( you can only forward if you rewind before )
here's the code
public class MainActivity extends Activity implements View.OnClickListener {
private final String TAG = "Main";
private Button buttonPlay;
private MediaPlayer player;
private boolean paused = false;
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
private Button forward, rewind;
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.volume);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
initControls();
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
buttonPlay = (Button) findViewById(R.id.buttonPlay);
rewind = (Button) findViewById(R.id.rewind);
forward = (Button) findViewById(R.id.forward);
buttonPlay.setOnClickListener(this);
rewind.setOnClickListener(this);
forward.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
if(!player.isPlaying())
{
Log.d(TAG,"Encender");
if(!paused) {
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
else
player.start();
}
else
{
Log.d(TAG,"Pausar");
player.pause();
paused = true;
}
}
if(v==rewind){
Log.d(TAG,"RW");
if(player.isPlaying()){
//TODO: CODE FOR REWIND
}
}
if( v== forward){
Log.d(TAG,"FW");
if(player.isPlaying()){
//TODO: CODE FOR FORWARD
}
}
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("MYURL");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showOKDialog(Activity ac, String msg){
AlertDialog.Builder builder = new AlertDialog.Builder(ac);
builder.setMessage(msg)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
could you help me with this please?
anybody knows an appropriate way to do this?
Thanks!

Android back to main activity from MusicService notification

I'm working on a music player for android and i'm stuck at this problem.
By now i can play a song with musicservice and send it to background, i also display a notification with current playing song.
What i need is to re-open the main activity from the song notification and continue playing the song, it actually starts the desired activity but the music service is re-created and it stops the current playing song.
Here is my code.
MusicService.java
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
private final IBinder musicBind = new MusicBinder();
//media player
private MediaPlayer player;
//song list
private ArrayList<SongModel> songs;
//current position
private int songPosition;
public MusicService() {
}
public void onCreate() {
//create the service
super.onCreate();
//initialize position
songPosition = 0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
//set player properties
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<SongModel> theSongs) {
songs = theSongs;
}
public class MusicBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public int getPosition() {
return player.getCurrentPosition();
}
public int getCurrenListPosition() {
return songPosition;
}
public int getDuration() {
return player.getDuration();
}
public boolean isPlaying() {
return player.isPlaying();
}
public void pausePlayer() {
player.pause();
}
public void stopPlayer() {
player.stop();
}
public void seekToPosition(int posn) {
player.seekTo(posn);
}
public void start() {
player.start();
}
public void playSong() {
try {
//play a song
player.reset();
SongModel playSong = songs.get(songPosition);
String trackUrl = playSong.getFileUrl();
player.setDataSource(trackUrl);
player.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer mp) {
if (mp.getCurrentPosition() == 0) {
mp.reset();
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
SongModel playingSong = songs.get(songPosition);
Intent intent = new Intent(this, NavDrawerMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_action_playing)
.setTicker(playingSong.getTitle())
.setOngoing(true)
.setContentTitle(playingSong.getTitle())
.setContentText(playingSong.getArtistName());
Notification notification = builder.build();
startForeground((int) playingSong.getSongId(), notification);
}
#Override
public void onDestroy() {
stopForeground(true);
}
public void setSong(int songIndex) {
songPosition = songIndex;
}
}
DiscoverSongsFragment.java
public class DiscoverSongsFragment extends Fragment
implements MediaController.MediaPlayerControl {
JazzyGridView songsContainer;
SongsHelper songsHelper;
SongsAdapter songsAdapter;
ArrayList<SongModel> songsArrayList;
ConnectionState connectionState;
Context mContext;
private static View rootView;
SongModel currentSong;
SeekBar nowPlayingSeekBar;
final Handler handler = new Handler();
// this value contains the song duration in milliseconds.
// Look at getDuration() method in MediaPlayer class
int mediaFileLengthInMilliseconds;
View nowPlayingLayout;
boolean nowPlayingLayoutVisible;
TextView nowPlayingTitle;
TextView nowPlayingArtist;
ImageButton nowPlayingCover;
ImageButton nowPlayingStop;
private MusicService musicService;
private Intent playIntent;
private boolean musicBound = false;
private boolean playbackPaused = false;
private int mCurrentTransitionEffect = JazzyHelper.SLIDE_IN;
public static DiscoverSongsFragment newInstance() {
return new DiscoverSongsFragment();
}
public DiscoverSongsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_discover_songs, container, false);
mContext = rootView.getContext();
setupViews(rootView);
return rootView;
}
#Override
public void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(mContext, MusicService.class);
mContext.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
mContext.startService(playIntent);
}
}
#Override
public void onResume() {
super.onResume();
if (isPlaying()) {
showNowPlayingLayout();
primarySeekBarProgressUpdater();
}
}
#Override
public void onDestroy() {
mContext.stopService(playIntent);
musicService = null;
super.onDestroy();
}
private void hideNowPlayingLayout() {
nowPlayingLayoutVisible = false;
nowPlayingLayout.setVisibility(View.GONE);
Animation animationFadeIn = AnimationUtils.loadAnimation(mContext, R.anim.fade_out);
nowPlayingLayout.startAnimation(animationFadeIn);
}
private void showNowPlayingLayout() {
nowPlayingLayoutVisible = true;
nowPlayingLayout.setVisibility(View.VISIBLE);
Animation animationFadeIn = AnimationUtils.loadAnimation(mContext, R.anim.fade_in);
nowPlayingLayout.startAnimation(animationFadeIn);
}
private void setupViews(View rootView) {
songsHelper = new SongsHelper();
songsArrayList = new ArrayList<SongModel>();
connectionState = new ConnectionState(mContext);
songsAdapter = new SongsAdapter(mContext, songsArrayList);
nowPlayingLayout = rootView.findViewById(R.id.nowPlayingLayout);
nowPlayingLayout.setVisibility(View.GONE);
nowPlayingLayoutVisible = false;
songsContainer = (JazzyGridView) rootView.findViewById(R.id.songsContainerView);
songsContainer.setTransitionEffect(mCurrentTransitionEffect);
songsContainer.setAdapter(songsAdapter);
songsContainer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
musicService.setSong(position);
musicService.playSong();
if (playbackPaused) {
playbackPaused = false;
}
currentSong = songsArrayList.get(position);
// gets the song length in milliseconds from URL
mediaFileLengthInMilliseconds = getDuration();
if (currentSong != null) {
nowPlayingTitle.setText(currentSong.getTitle());
nowPlayingArtist.setText(currentSong.getArtistName());
nowPlayingCover.setImageBitmap(currentSong.getCoverArt());
}
primarySeekBarProgressUpdater();
if (!nowPlayingLayoutVisible) {
showNowPlayingLayout();
}
}
});
nowPlayingSeekBar = (SeekBar) rootView.findViewById(R.id.nowPlayingSeekbar);
nowPlayingSeekBar.setMax(99);
nowPlayingTitle = (TextView) rootView.findViewById(R.id.nowPlayingTitle);
nowPlayingArtist = (TextView) rootView.findViewById(R.id.nowPlayingArtist);
nowPlayingStop = (ImageButton) rootView.findViewById(R.id.nowPlayingStop);
nowPlayingStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPlaying()) {
currentSong = null;
playbackPaused = false;
musicService.stopPlayer();
mediaFileLengthInMilliseconds = 0;
nowPlayingSeekBar.setProgress(0);
hideNowPlayingLayout();
}
}
});
nowPlayingCover = (ImageButton) rootView.findViewById(R.id.nowPlayingCover);
nowPlayingCover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(mContext, SongDetailsActivity.class);
intent.putExtra("Title", currentSong.getTitle());
intent.putExtra("Artist", currentSong.getArtistName());
intent.putExtra("Album", currentSong.getAlbumName());
intent.putExtra("Genre", currentSong.getGenre());
intent.putExtra("CoverUrl", currentSong.getCoverArtUrl());
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
getSongs();
hideNowPlayingLayout();
}
private void getSongs() {
if (!connectionState.isConnectedToInternet()) {
}
songsAdapter.clear();
String songsUrl = Constants.getAPI_SONGS_URL();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(songsUrl, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SongModel song = songsHelper.getSongFromJson(jsonObject);
songsAdapter.add(song);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
/**
* Method which updates the SeekBar primary progress by current song playing position
*/
private void primarySeekBarProgressUpdater() {
nowPlayingSeekBar.setProgress((int) (((float) getCurrentPosition() / getDuration()) * 100));
//if (isPlaying()) {
Runnable runnable = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(runnable, 1000);
//}
}
#Override
public void start() {
musicService.start();
}
#Override
public void pause() {
playbackPaused = true;
musicService.pausePlayer();
}
#Override
public int getDuration() {
if (musicService != null && musicBound && musicService.isPlaying()) {
return musicService.getDuration();
}
return 0;
}
#Override
public int getCurrentPosition() {
if (musicService != null && musicBound && musicService.isPlaying()) {
return musicService.getPosition();
}
return 0;
}
public int getCurrentListPosition() {
if (musicService != null && musicBound && musicService.isPlaying()) {
return musicService.getCurrenListPosition();
}
return 0;
}
#Override
public void seekTo(int pos) {
musicService.seekToPosition(pos);
}
#Override
public boolean isPlaying() {
if (musicService != null && musicBound && musicService.isPlaying()) {
return musicService.isPlaying();
}
return false;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
//get service
musicService = binder.getService();
//pass list
musicService.setList(songsArrayList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
}
(The fragment also re-creates itself when navigating through drawer menu items)
I hope somebody can help me achieve this. I dont know how to maintane the state when re-starting the MainActivity (by the way, im using navdrawer to hold fragments)
Include the currently playing song in your notification intent. Update the intent as the song changes. Include the flag to clear top and the flag to update current in the notification intent. :( sorry IDK if I have the flags right for your situation but you'll have a place to do more research.
In your service where you create the notification intent.
// link the notifications to the recorder activity
Intent resultIntent = new Intent(context, KmlReader.class);
resultIntent
.setAction(ServiceLocationRecorder.INTENT_COM_GOSYLVESTER_BESTRIDES_LOCATION_RECORDER);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultPendingIntent = PendingIntent
.getActivity(context, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
return mBuilder.build();
}
Then in main onCreate check the bundle for the name of the currently playing song and display it. Notice how I check for the existence of a bundle key before using it.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String intentaction = intent.getAction();
// First Run checks
if (savedInstanceState == null) {
// first run init
...
} else {
// get the saved_Instance state
// always get the default when key doesn't exist
// default is null for this example
currentCameraPosition = savedInstanceState
.containsKey(SAVED_INSTANCE_CAMERA_POSITION) ? (CameraPosition) savedInstanceState
.getParcelable(SAVED_INSTANCE_CAMERA_POSITION) : null;
...

Show Text in TextView when video reaches current time Android

I want to make a text appear in TextView when the video reaches current time. I've tried this code :
public class VideoActivity extends Activity {
private static final String MY_AD_UNIT_ID = null;
protected static final String TAG = null;
private AdView adView;
int waktu;
Button btncek;
private MediaController controller = null;
TextView textView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videoplayer);
Bundle bundle = getIntent().getExtras();
String urlbarus = getIntent().getStringExtra("urlbaru");
final VideoView videoView = (VideoView) findViewById(R.id.videoView1);
videoView.setVideoPath(urlbarus);
MediaController.MediaPlayerControl mcEvents = new MediaController.MediaPlayerControl() {
public void start() {
videoView.start();
}
public void seekTo(int pos) {
videoView.seekTo(pos);
}
public void pause() {
videoView.pause();
}
public boolean isPlaying() {
return videoView.isPlaying();
}
public int getDuration() {
return videoView.getDuration();
}
public int getCurrentPosition() {
return videoView.getCurrentPosition();
}
public boolean canSeekForward() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canPause() {
return true;
}
#Override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
};
controller = new MediaController(this);
controller.setMediaPlayer(mcEvents);
controller.setAnchorView(findViewById(R.id.wrapper));
videoView.start();
if(mcEvents.getCurrentPosition()>=10000){
textView2.setText("kebaca");
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//the MediaController will hide after 3 seconds - tap the screen to make it appear again
controller.show();
return false;
}
This is the code for showing text :
if(mcEvents.getCurrentPosition()>=10000){
textView2.setText("kebaca");
}
I have tried that code, but nothing happens (textview2 does not show the text)
Can anyone help me?
Try something like..
final MediaController.MediaPlayerControl mcEvents = ....
textView2.setText(""); // edited
new Thread(new Runnable() {
#Override
public void run() {
while (mcEvents.getCurrentPosition()<10000){
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) { }
}
runOnUiThread(new Runnable() {
#Override
public void run() {
textView2.setText("kebaca");
}
});
}
}).start();

Categories

Resources