I have radio app stream, and when open this app, first its open splash layout like this :
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/loading" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.67" />
</LinearLayout>
and class for it like :
StartPoint.java
public class StartPoint extends Activity{
ProgressBar progressBar;
private int progressBarStatus = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
while(progressBarStatus < 5000){
StartPoint.this.runOnUiThread(new Runnable(){
public void run()
{
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
});
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openMainList = new Intent(StartPoint.this,
com.example.kam.MainActivity.class);
startActivity(openMainList);
}
}
};
timer.start();
}
#Override
protected void onStop(){
super.onStop();
finish();
}
}
this class when finished, its call MainActivity.java class, and its show :
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
// Define ..............................................................
private static ProgressDialog progressDialog;
public MediaPlayer mp;
boolean isPrepared = false;
Button PlayBtn, ExitBtn, PauseBtn, RefreshBtn;
String MEDIA_PATH;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = ProgressDialog.show(MainActivity.this, "",
"Buffering Radio...", true);
progressDialog.setCancelable(false);
// Declare
// ..............................................................
mp = new MediaPlayer();
PlayBtn = (Button) findViewById(R.id.btnPlay);
PlayBtn.setOnClickListener(this);
PauseBtn = (Button) findViewById(R.id.btnPause);
PauseBtn.setOnClickListener(this);
RefreshBtn = (Button) findViewById(R.id.btnRefresh);
RefreshBtn.setOnClickListener(this);
ExitBtn = (Button) findViewById(R.id.btnExit);
ExitBtn.setOnClickListener(this);
MEDIA_PATH = "http://radio.arabhosters.com:8015/";
// Volume Control
// ..............................................................
final AudioManager leftAm = (AudioManager)
getSystemService(Context.AUDIO_SERVICE);
int maxVolume = leftAm.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = leftAm.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar) findViewById(R.id.volumebar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener
(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged
(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
leftAm.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
}
});
}
#Override
public void onClick(View v) {
if (v == PlayBtn) {
startradio();
}
else if (v == PauseBtn) {
pauseradio();
}
else if (v == ExitBtn) {
exitradio();
}
else if (v == RefreshBtn) {
try {
refreshradio();
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onCompletion(MediaPlayer mediaPlayer) {
synchronized (this) {
isPrepared = false;
}
}
protected void onResume() {
super.onResume();
try {
mp.setDataSource(MEDIA_PATH);
}
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();
}
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.prepare();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // also consider mp.prepareAsync().
// defult start stream when start App.
mp.start();
mp.setVolume(100, 100);
progressDialog.dismiss();
}
// method for play stream after stop it.
public void startradio() {
try {
if (mp.isPlaying()) {
return;
}
mp.start();
progressDialog.dismiss();
}
catch (IllegalStateException ex) {
ex.printStackTrace();
}
}
// method for Refresh stream.
public void refreshradio() throws IllegalArgumentException,
SecurityException, IOException {
try {
if (mp.isPlaying()) {
return;
}
mp.reset();
mp.setDataSource(MEDIA_PATH);
mp.prepare();
mp.start();
progressDialog.dismiss();
}
catch (IllegalStateException ex) {
ex.printStackTrace();
}
}
// method for pause stream.
public void pauseradio() {
mp.pause();
}
// method for check is radio paly or not stream
public boolean isPlaying() {
return mp.isPlaying();
}
// method for Looping audio if your record it - Soon :)
public boolean isLooping() {
return mp.isLooping();
}
// method for Looping audio if your record it - Soon :)
public void setLooping(boolean isLooping) {
mp.setLooping(isLooping);
}
// method for volume
public void setVolume(float volumeLeft, float volumeRight) {
mp.setVolume(volumeLeft, volumeRight);
}
// method for stop stream.
public void stopradio() {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
}
// method for exit.
public void exitradio() {
finish();
System.exit(0);
}
// method for back to main menu "Home".
public void backtomenu() {
finish();
}
#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;
}
}
and layout for it like :
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical"
>
<LinearLayout
android:layout_weight="6"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="fill_parent"
android:layout_height="0dip" >
</LinearLayout>
<LinearLayout
android:id="#+id/buttons"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_alignParentLeft="true"
android:layout_weight="0.62"
android:background="#drawable/iconbgrepate"
android:gravity="center"
android:orientation="horizontal"
android:tileMode="repeat"
android:weightSum="5"
android:alpha=".75">
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/volumebar"
android:max="100"
android:paddingBottom="10dip"/>
</LinearLayout>
<LinearLayout
android:id="#+id/buttons"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_alignParentLeft="true"
android:layout_weight="0.62"
android:background="#drawable/iconbgrepate"
android:gravity="center"
android:orientation="horizontal"
android:tileMode="repeat"
android:weightSum="5" >
<Button
android:id="#+id/btnRefresh"
android:layout_width="32dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="0.10"
android:background="#drawable/refreshbutton" />
<View android:layout_weight="1"
android:layout_width="0dip"
android:layout_height="0dip" />
<Button
android:id="#+id/btnPause"
android:layout_width="32dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="0.05"
android:background="#drawable/pausebutton" />
<View android:layout_weight="1"
android:layout_width="0dip"
android:layout_height="0dip" />
<Button
android:id="#+id/btnPlay"
android:layout_width="32dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="0.05"
android:background="#drawable/playbutton" />
<View android:layout_weight="1"
android:layout_width="0dip"
android:layout_height="0dip" />
<Button
android:id="#+id/btnExit"
android:layout_width="32dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="0.12"
android:background="#drawable/exitbutton" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
why when trans from splash.xml to activity_main.xml display black background few min and display app.
Since you are changing activity, its gonna show some animation or black screen like you said. Its the default behavior. You can use a custom dialog with your splash layout on top of main activity. you can trigger the dialog to close on progress complete. Using two activities can have other effects. for instance when the user hits the back button, its gonna go back to splash screen instead of exiting the app.
try it
Thread timer = new Thread(){
public void run(){
try{
while(progressBarStatus < 5000){
StartPoint.this.runOnUiThread(new Runnable(){
public void run()
{
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
});
sleep(5000);
}
Related
I'm working in video view that contain title layout. I have attached the header layout in video view. what is my problem is when i touch on video view both title layou and mediacontolls should shown, After some time both(title layou and media controls) should disappear. Simply whenever the media controlls show the title layou should show , then whenever media controlls disapper the title layou should disapper.
XML CODE
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#000">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent">
<VideoView
android:id="#+id/playerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:layout_gravity="center_vertical" />
<LinearLayout
android:id="#+id/share_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:padding="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="80dp"
android:orientation="horizontal">
<ImageButton
android:id="#+id/twitter_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/twitter"
android:paddingTop="20dp"
android:paddingRight="10dp"
android:background="#android:color/transparent" />
<ImageButton
android:id="#+id/facebook_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/facebook"
android:paddingRight="10dp"
android:layout_below="#+id/twitter_button"
android:background="#android:color/transparent"
android:paddingTop="20dp"/>
<ImageButton
android:visibility="gone"
android:id="#+id/share_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/share_icon"
android:background="#android:color/transparent"
android:paddingTop="20dp"
android:layout_below="#+id/facebook_button"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#BF000000"
android:padding="10dp">
<ImageButton
android:id="#+id/imageBtnclose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/close_button"
android:background="#android:color/transparent" />
<TextView
android:id="#+id/videoTitletv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="video title"
android:textColor="#ffffff"
android:paddingLeft="10dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageBtnclose"
android:layout_toEndOf="#+id/imageBtnclose" />
</RelativeLayout>
JAVA CODE
public class VideoAdPlayer extends Activity {
// private boolean vbBackkeyPressed = false;
private VideoView myVideoView;
private RelativeLayout myLinearClose;
LinearLayout shareLayout;
private ProgressDialog progressDialog;
private MediaController mediaControls;
private int adshowTime = 30;
Timer mTimer = new Timer();
boolean MidrollPlayed = false;
YuMeInterface yumeInterface;
ImageButton imgCloseBtn;
boolean isPortrait = true;
ImageButton faceBookButton, twitterButton, shareButton;
public static VideoAdPlayer playerActivity = null;
public static Context playerContext = null;
public static int playedAdType = 1;
public static boolean isActivityrun = false;
boolean isPrerollAds;
boolean isPostrollAds;
boolean isMidrollAds;
boolean isShareClicked = false;
#SuppressLint("ClickableViewAccessibility")
#SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String myString = android.os.Build.VERSION.RELEASE;
System.out.println(myString);
setContentView(R.layout.video);
Intent intent = getIntent();
String playVideoUrl = "";
String videoThumb = "";
getActionBar().hide();
playerActivity = this;
playerContext = this.getApplicationContext();
myLinearClose = (RelativeLayout) findViewById(R.id.header_layout);
shareLayout = (LinearLayout) findViewById(R.id.share_layout);
TextView videoTxtview = (TextView)findViewById(R.id.videoTitletv);
faceBookButton = (ImageButton) findViewById(R.id.facebook_button);
twitterButton = (ImageButton) findViewById(R.id.twitter_button);
shareButton = (ImageButton) findViewById(R.id.share_Button);
shareLayout.setOrientation(LinearLayout.HORIZONTAL);
videoTxtview.setText("DEFAULT TITLE");
if (mediaControls == null) {
mediaControls = new MediaController(VideoAdPlayer.this);
}
myVideoView = (VideoView) findViewById(R.id.playerview);
imgCloseBtn = (ImageButton) findViewById(R.id.imageBtnclose);
progressDialog = createProgressDialog(VideoAdPlayer.this);
progressDialog.show();
imgCloseBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
JSONObject msgPlayer = new JSONObject();
try {
msgPlayer.put("finished", false);
YumeIntegration.callbackContext.success(msgPlayer);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
});
try {
myVideoView.setVideoURI(Uri.parse(playVideoUrl));
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
myVideoView.requestFocus();
myVideoView.setZOrderOnTop(false);
playedAdType = 1;
myVideoView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (!myLinearClose.isShown()) {
if (!isPortrait) {
myLinearClose.setVisibility(View.VISIBLE);
}
myLinearClose.postDelayed(new Runnable() {
#Override
public void run() {
if (!isPortrait) {
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}, 3000);
} else {
if (myLinearClose.isShown()) {
if (!isPortrait) {
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}
return false;
}
});
myVideoView.setMediaController(mediaControls);
myVideoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(final MediaPlayer mediaPlayer) {
progressDialog.dismiss();
myLinearClose.setVisibility(View.VISIBLE);
int duration = myVideoView.getDuration();
Log.e("total duration", String.valueOf(duration));
final int totalSeconds = duration / 1000;
final int postrollads = totalSeconds - 25;
final int MidrollAdsShows = totalSeconds / 2;
Log.e("total durationin secods", String.valueOf(totalSeconds));
try {
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
int currentTime = myVideoView.getCurrentPosition() / 1000;
/*
* if (currentTime > postrollads &&
* !postRolladsInit) { postRolladsInit = true; try {
* yumeInterface.updatesSdkParams(3); } catch
* (YuMeException e) { e.printStackTrace(); }
*
* } */
if (currentTime > MidrollAdsShows && !MidrollPlayed) {
adshowTime += 30;
MidrollPlayed = true;
playedAdType = 2;
if (isMidrollAds) {
if (yumeInterface.sdkIsAdAvailable()) {
myVideoView.pause();
final Intent mainIntent = new Intent(VideoAdPlayer.this, AdView.class);
startActivityForResult(mainIntent, 3);
}
}
}
}
}, 0, 2000);
if (!mediaControls.isShowing()) {
mediaControls.show();
Toast.makeText(VideoAdPlayer.this,"YES",Toast.LENGTH_SHORT).show();
}
myLinearClose.setVisibility(View.VISIBLE);
myLinearClose.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (!isPortrait){
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}, 3000);
} catch (Exception ex) {
}
}
});
myVideoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mTimer.cancel();
JSONObject msgPlayer = new JSONObject();
try {
msgPlayer.put("finished", true);
YumeIntegration.callbackContext.success(msgPlayer);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playedAdType = 3;
// finish();
if (isPostrollAds) {
if (yumeInterface.sdkIsAdAvailable()) {
final Intent mainIntent = new Intent(VideoAdPlayer.this, AdView.class);
startActivityForResult(mainIntent, 3);
} else {
finish();
}
} else {
finish();
}
}
});
public static ProgressDialog createProgressDialog(Context mContext) {
ProgressDialog dialog = new ProgressDialog(mContext);
try {
dialog.show();
} catch (BadTokenException e) {
}
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.progressdialog);
// dialog.setMessage(Message);
return dialog;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 3
if (requestCode == 3) {
myVideoView.requestFocus();
myVideoView.start();
myVideoView.setZOrderOnTop(false);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
myLinearClose.setVisibility(View.VISIBLE);
shareLayout.setOrientation(LinearLayout.VERTICAL);
myVideoView.requestFocus();
isPortrait = false;
landscapeMode();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
shareLayout.setOrientation(LinearLayout.HORIZONTAL);
myVideoView.requestFocus();
isPortrait = true;
myLinearClose.setVisibility(View.VISIBLE);
portraitMode();
}
}
private void portraitMode() {
isPortrait = true;
faceBookButton.setVisibility(View.VISIBLE);
twitterButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.GONE);
if (!mediaControls.isShowing()) {
mediaControls.show();
Toast.makeText(VideoAdPlayer.this, "YES", Toast.LENGTH_SHORT).show();
}
myLinearClose.setVisibility(View.VISIBLE);
myLinearClose.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (!isPortrait) {
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}, 3000);
}
private void landscapeMode() {
isPortrait = false;
if (!mediaControls.isShowing()) {
mediaControls.show();
Toast.makeText(VideoAdPlayer.this, "YES", Toast.LENGTH_SHORT).show();
}
myLinearClose.setVisibility(View.VISIBLE);
myLinearClose.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (!isPortrait) {
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}, 3000);
faceBookButton.setVisibility(View.GONE);
twitterButton.setVisibility(View.GONE);
shareButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!isPortrait) {
if (!isShareClicked) {
isShareClicked = true;
faceBookButton.setVisibility(View.GONE);
twitterButton.setVisibility(View.GONE);
} else {
isShareClicked = false;
faceBookButton.setVisibility(View.VISIBLE);
twitterButton.setVisibility(View.VISIBLE);
}
}
}
});
}
I want to show a ProgressBar while MediaPlayer is preparing to play and when MediaPlayer starts playing ProgressBar disappear .
this is my code
public class MainActivity extends Activity {
String path="http://live.mp3quran.net:8006/;";
Button play_button, pause_button;
MediaPlayer player =new MediaPlayer();
private ProgressBar mProgress;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play_button=(Button)findViewById(R.id.play_button);
pause_button=(Button)findViewById(R.id.pause_button);
mProgress=(ProgressBar)findViewById(R.id.progressBar);
mProgress.setVisibility(View.INVISIBLE);
play_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProgress.setVisibility(View.VISIBLE);
try {
player.setDataSource(path);
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(mProgress.getVisibility()==View.VISIBLE)
mProgress.setVisibility(View.INVISIBLE);
}
}
});
pause_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player.stop();
player.reset();
}
});
}
}
my XML file Code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<Button android:id="#+id/play_button"
android:layout_width="120px"
android:layout_height="60px"
android:layout_marginTop="60px"
android:gravity="center"
android:text="Play" />
<Button android:id="#+id/pause_button"
android:layout_width="120px"
android:layout_height="60px"
android:layout_alignParentRight="true"
android:layout_marginTop="60px"
android:text="Pause" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_alignBottom="#+id/text_shown"
android:layout_toRightOf="#+id/play_button"
android:layout_toLeftOf="#+id/pause_button"
android:max="100"
android:progress="20"
android:layout_toStartOf="#+id/pause_button" />
</RelativeLayout>
My problem is that ProgressBar doesn't appear.
I have tried this solution
How can i show a ProgressBar when mediaPlayer is prepairing to play
but it doesn't help.
You can use like this
final ProgressDialog ringProgressDialog = ProgressDialog.show(this, "Please wait ...", "Fetching your contact..", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
// Here you should write your time consuming task...
// Let the progress ring for 10 seconds...
readContact();
// Thread.sleep(300);
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
Im rotating a LinearLayout, using an ObjectAnimator. Clicking the button causes the LinearLayout to rotate 360(degrees) with the bottom part as the Pivot.
After the Layout completes the rotation, it leaves back a 'trail'/black mark and the complete view looks odd. How do I avoid this from happening? After the Layout completes the 360 animation, I want the view to look as it did in the beginning (clean basically).
Is there a view.refresh or update command im suppose to call somewhere?
1)How do I have a clean looking view at the end?
2)When the image is is in the intermediatestate, why does the back-part appear black? How do I get that to look while(ie,color of the relative layout)?
InitialState>IntermediateState>FinalState:
MainActivity
Button bt1;
float pivotX=0f;
float pivotY=0f;
int a=0;
float width,height;
ViewGroup mContainer=null;
Thread t;
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button) findViewById(R.id.button1);
mContainer = (ViewGroup) findViewById(R.id.container);
bt1.setOnClickListener(this);
t=new Thread()
{
#Override
public void run()
{
try {
while(true)
{
relativeLayout.postInvalidate();
}
} catch (Exception e) {
// TODO: handle exception
}
}
};
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
//Here you can get the size!
width = mContainer.getWidth();
height = mContainer.getHeight();
pivotX = mContainer.getPivotX()+width;
pivotY = mContainer.getPivotY()+height;
mContainer.setPivotX(pivotX);
mContainer.setPivotY(pivotY);
}
private void rotate()
{
a -=360;
ObjectAnimator rotate = ObjectAnimator.ofFloat(mContainer, View.ROTATION_X,a);
rotate.setDuration(2000);
AnimatorSet aSet = new AnimatorSet();
aSet.play(rotate);
aSet.start();
mHandler.post(new Runnable()
{
#Override
public void run()
{
b+=1;
relativeLayout.invalidate();
relativeLayout.postInvalidate();
bt1.setText(Integer.toString(b));
}
});
rotate.addListener(new AnimatorListener()
{
#Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
//relativeLayout.invalidate();
t.start();
}
#Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
//mContainer.invalidate();
//relativeLayout.invalidate();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.button1:
rotate();
break;
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#140A1F"
android:orientation="horizontal" >
</LinearLayout>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/container"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:text="Rotate" />
</RelativeLayout>
Edit: Added a thread.
**Edit2:**** Added a handler and commented out the thread
Adding this to the code fixes the view once the animation is competed, but the intermediate stage still looks the same. Will update this once I figure that out.
rotate.addListener(new AnimatorListener()
{
#Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
relativeLayout.invalidate();
}
#Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
//mContainer.invalidate();
relativeLayout.invalidate();
}
#Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
});
How could I make it so that my MediaPlayer continues to play even when the phone is locked and the screen is off, thinking it may have to do something of making it a service but not sure. If so how could I go about changing it to a service or is there a quicker easier fix?
Any help would be great!
Here is code:
public class player2 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_2);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound04; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound05; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound06;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player2.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
static boolean runThread = true;
public void run() {
while ( runThread ) {
int currentPosition=0;
int total = mp.getDuration();
if ( mp != null && currentPosition <= total ) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
} else
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
runThread = false;
}
#Override
protected void onStop() {
super.onStop();
if (mp != null && mp.isPlaying()){
mp.pause();
}
}
#Override
public void onResume()
{
super.onResume();
if (mp != null){
if(!mp.isPlaying())
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Follow my tutorial below...In following tutorial i have stored .mp3 file in raw folder. if you have stored it in sd card and dynamically fetching that file then put its path in bundle and send it through intent which you can get in onStartCommand() method of your service.
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
Button startPlaybackButton, stopPlaybackButton;
Intent playbackServiceIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);
startPlaybackButton.setOnClickListener(this);
stopPlaybackButton.setOnClickListener(this);
playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
}
public void onClick(View v) {
if (v == startPlaybackButton) {
startService(playbackServiceIntent);
finish();
} else if (v == stopPlaybackButton) {
stopService(playbackServiceIntent);
finish();
}
}
}
BackgroundAudioService.java
public class BackgroundAudioService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mediaPlayer = MediaPlayer.create(this, R.raw.abc);// YOUR FILE NAME
mediaPlayer.setOnCompletionListener(this);
Log.v("TEST", "1");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
Log.v("TEST", "2");
mediaPlayer.start();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
activity_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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Background Audio Player"
/>
<Button android:text="Start Playback" android:id="#+id/StartPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Stop Playback" android:id="#+id/StopPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
Don't forget to declare Service in manifest.xml like below,
<service android:name="com.demo.tute.BackgroundAudioService" />
I'm new to Android and I'm trying to make a really simple app. Its just one activity which contains a MediaPlayer for playing audio or video files.
I managed to play a song, but it just won't show me the control elements of the media player!
Here is the code I am using:
public class Player extends Activity implements OnPreparedListener,
MediaPlayerControl {
private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private String audioFile;
private MediaPlayer mediaPlayer;
private Handler handler = new Handler();
private MediaController mediaController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Uri myUri = Uri.parse("android.resource://com.example.mediaplayer/"
+ R.raw.lied); // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(getApplicationContext(), myUri);
} 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();
}
mediaPlayer.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.player, menu);
return true;
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.mediaController1));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
protected void onStop() {
super.onStop();
mediaPlayer.stop();
mediaPlayer.release();
}
public boolean onTouchEvent(MotionEvent event) {
// the MediaController will hide after 3 seconds - tap the screen to
// make it appear again
mediaController.show();
return false;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public void pause() {
mediaPlayer.pause();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public void start() {
mediaPlayer.start();
}
}
And here is my Layout XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Player" >
<MediaController
android:id="#+id/mediaController1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="122dp"
android:layout_marginTop="55dp"
android:visibility="visible" >
</MediaController>
<VideoView
android:id="#+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
I think what your looking for is a videoview in Android. It has default controls when playing media.
Create a videoview in your XML layout folder like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<VideoView
android:id="#+id/myvideoview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Let's say you called that file main.xml
Now create an activity called MediaViewerTest.java like this:
public class MediaViewerTest extends Activity {
String SrcPath = http://myMediaFile.mp3"; // or however your getting your media source, im assuming web here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
VideoView myVideoView = (VideoView)findViewById(R.id.myvideoview);
myVideoView.setVideoURI(Uri.parse(SrcPath));
myVideoView.setMediaController(new MediaController(this));
myVideoView.requestFocus();
myVideoView.start();
}
}