Java tutorial
/* * </summary> * Source File : PlayerActivity.java * Project : Sarigama * Owner : Kasun * </summary> * * <license> * Copyright 2016 Kasun Gunathilaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </license> */ package com.kasungunathilaka.sarigama.ui; import android.app.Activity; import android.app.ProgressDialog; 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.media.MediaPlayer; import android.os.Handler; import android.os.IBinder; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.kasungunathilaka.sarigama.R; import com.kasungunathilaka.sarigama.service.PlayerService; import com.squareup.picasso.Picasso; import java.io.IOException; import de.hdodenhof.circleimageview.CircleImageView; public class PlayerActivity extends AppCompatActivity { // private MediaPlayer mediaPlayer; private SeekBar seekBar; private ImageButton ibPlay; PlayerService playerService; BroadcastReceiver broadcastReceiver; boolean isBound = false; ProgressDialog dialog; String audioFile = ""; public final static String AUDIO_URL = "audio_url"; public final static String AUDIO_TITLE = "audio_title"; public final static String AUDIO_ARTIST = "audio_artist"; public final static String IMG_URL = "image_url"; public final static String ON_PREPARED = "com.kasungunathilaka.sarigama.ON_PREPARED"; public final static String ON_COMPLETED = "com.kasungunathilaka.sarigama.ON_COMPLETED"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); Intent intent = getIntent(); audioFile = intent.getStringExtra(AUDIO_URL); final String coverImage = intent.getStringExtra(IMG_URL); final String audioTitle = intent.getStringExtra(AUDIO_TITLE); final String audioArtist = intent.getStringExtra(AUDIO_ARTIST); // mediaPlayer = new MediaPlayer(); try { // mediaPlayer.setDataSource(audioFile); // mediaPlayer.prepareAsync(); dialog = new ProgressDialog(PlayerActivity.this); dialog.setMessage(getString(R.string.loading)); dialog.setCancelable(false); dialog.getWindow().setGravity(Gravity.CENTER); dialog.show(); setContentView(R.layout.activity_player); ((TextView) findViewById(R.id.tvTitle)).setText(audioTitle); ((TextView) findViewById(R.id.tvArtist)).setText(audioArtist); ImageView mImageView = (ImageView) findViewById(R.id.coverImage); String image_url = coverImage; Picasso.with(getApplicationContext()).load(image_url).into(mImageView); // mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // public void onPrepared(final MediaPlayer mp) { // mp.start(); // ((CircleImageView) findViewById(R.id.ibPlay)).setImageResource(R.drawable.ic_pause_white); // seekBar = (SeekBar) findViewById(R.id.seekBar); // mRunnable.run(); // dialog.dismiss(); // } // }); // // mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { // @Override // public void onCompletion(MediaPlayer mp) { // ((CircleImageView) findViewById(R.id.ibPlay)).setImageResource(R.drawable.ic_play_white); // } // }); } catch (Exception e) { Activity a = this; a.finish(); Toast.makeText(this, getString(R.string.file_not_found), Toast.LENGTH_SHORT).show(); } broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case ON_PREPARED: ((CircleImageView) findViewById(R.id.ibPlay)).setImageResource(R.drawable.ic_pause_white); seekBar = (SeekBar) findViewById(R.id.seekBar); mRunnable.run(); dialog.dismiss(); break; case ON_COMPLETED: ((CircleImageView) findViewById(R.id.ibPlay)).setImageResource(R.drawable.ic_play_white); seekBar.setProgress(0); break; } } }; } private Handler mHandler = new Handler(); private Runnable mRunnable = new Runnable() { @Override public void run() { if (isBound) { int mDuration = playerService.getDuration(); seekBar.setMax(mDuration); TextView totalTime = (TextView) findViewById(R.id.totalTime); totalTime.setText(getTimeString(mDuration)); int mCurrentPosition = playerService.getCurrentPosition(); seekBar.setProgress(mCurrentPosition); TextView currentTime = (TextView) findViewById(R.id.currentTime); currentTime.setText(getTimeString(mCurrentPosition)); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { playerService.seekTo(progress); } } }); } mHandler.postDelayed(this, 10); } }; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); } return super.onOptionsItemSelected(item); } public void play(View view) { if (playerService.isPlaying()) { ((CircleImageView) findViewById(R.id.ibPlay)).setImageResource(R.drawable.ic_play_white); playerService.setPlayPause(); } else { ((CircleImageView) findViewById(R.id.ibPlay)).setImageResource(R.drawable.ic_pause_white); playerService.setPlayPause(); } } public void stop(View view) { playerService.seekTo(0); playerService.setPlayPause(); } public void seekForward(View view) { // //set seek time // int seekForwardTime = 5000; // // // get current song position // int currentPosition = mediaPlayer.getCurrentPosition(); // // check if seekForward time is lesser than song duration // if (currentPosition + seekForwardTime <= mediaPlayer.getDuration()) { // // forward song // mediaPlayer.seekTo(currentPosition + seekForwardTime); // } else { // // forward to end position // mediaPlayer.seekTo(mediaPlayer.getDuration()); // } } public void seekBackward(View view) { // //set seek time // int seekBackwardTime = 5000; // // // get current song position // int currentPosition = mediaPlayer.getCurrentPosition(); // // check if seekBackward time is greater than 0 sec // if (currentPosition - seekBackwardTime >= 0) { // // forward song // mediaPlayer.seekTo(currentPosition - seekBackwardTime); // } else { // // backward to starting position // mediaPlayer.seekTo(0); // } } public void onBackPressed() { super.onBackPressed(); // if (mediaPlayer != null) { // mediaPlayer.reset(); // mediaPlayer.release(); // mediaPlayer = null; // } finish(); } private String getTimeString(long millis) { StringBuffer buf = new StringBuffer(); long hours = millis / (1000 * 60 * 60); long minutes = (millis % (1000 * 60 * 60)) / (1000 * 60); long seconds = ((millis % (1000 * 60 * 60)) % (1000 * 60)) / 1000; if (hours > 0) { buf.append(String.format("%02d", hours)).append(":").append(String.format("%02d", minutes)).append(":") .append(String.format("%02d", seconds)); } else { buf.append(String.format("%02d", minutes)).append(":").append(String.format("%02d", seconds)); } return buf.toString(); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, PlayerService.class); intent.putExtra(AUDIO_URL, audioFile); LocalBroadcastManager.getInstance(PlayerActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_PREPARED)); LocalBroadcastManager.getInstance(PlayerActivity.this).registerReceiver((broadcastReceiver), new IntentFilter(ON_COMPLETED)); } @Override protected void onStop() { super.onStop(); if (isBound) { unbindService(serviceConnection); isBound = false; } } private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { PlayerService.PlayerBinder binder = (PlayerService.PlayerBinder) service; playerService = binder.getService(); isBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { isBound = false; } }; @Override protected void onResume() { super.onResume(); } }