I have an Fragment which opens up a new activity in landscape mode which has a videoview to play a video. The problem s when the video is completed the activity with the video should finish and the control should automatically go back to the previous Fragment . Similar should be when the back button is pressed.
Currently, When the video gets completed it restarts and only when the second time it completes the control goes back to the previous Fragment . Same is with the back button press ie. I have o press the back button twice to finish the activity with the video.
Here is some code im doing:-
MainFragment
Intent mIntent = new Intent();
mIntent.AddFlags(ActivityFlags.ReorderToFront);
mIntent.AddFlags(ActivityFlags.NewTask);
mIntent.SetClass(this.Activity, typeof(VideoActivity));
Activity.StartActivity(mIntent);
VideoActivity
public class VideoActivity : Activity, Android.Media.MediaPlayer.IOnCompletionListener
{
private VideoView mVV;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
RequestWindowFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.VideoLayout);
// Create your application here
int fileRes = 0;
fileRes = Resource.Raw.trailer;
mVV = FindViewById<VideoView>(Resource.Id.myvideoview);
mVV.SetOnCompletionListener(this);
if(!mVV.IsPlaying)
{
if (!playFileRes(fileRes)) return;
MediaController mc = new MediaController(this);
mc.SetAnchorView(mVV);
mVV.SetMediaController(mc);
}
else
{
mVV.Suspend();
Finish();
}
}
private bool playFileRes(int fileRes)
{
if (fileRes == 0)
{
stopPlaying();
return false;
}
else
{
mVV.SetVideoURI(Android.Net.Uri.Parse("android.resource://" + PackageName + "/" + fileRes.ToString()));
return true;
}
}
public void stopPlaying()
{
mVV.StopPlayback();
this.Finish();
}
public void OnCompletion(Android.Media.MediaPlayer mp)
{
stopPlaying();
}
protected override void OnResume()
{
mVV.Resume();
}
protected override void OnPause()
{
stopPlaying();
}
public override void OnBackPressed()
{
stopPlaying();
}
}
How do I solve this? Any help would be appreciated.
Related
this is my Splash Screen, If I press home or multitasking/appswitch button when Intent is started app crash, in logcat is FATAL EXEPTION: Thread-1277. Can I kill/delete this Intent when player press home button?
public class SplashScreen extends Activity {
private static int loadingTime = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.loading_screen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, loadingTime);
}
}
The following code tracks whether the SplashActivity is at least partially showing. If yes, it will continue to MainActivity. If not (activity is finished by pressing Back button, activity is stopped by pressing Home button) nothing happens.
This solution uses Fragments so the timing is preserved across e.g. screen orientation changes (it will always take specified time no matter how many times you rotate your device - the timer will not reset).
public class SplashActivity extends Activity {
// tracks when the activity is at least partially visible (e.g. under a dialog)
private boolean mStarted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// your current code
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.activity_startup);
if (savedInstanceState == null) {
// first time onCreate, create fragment which starts countdown
getFragmentManager()
.beginTransaction()
.add(SplashFinishFragment.newInstance(), SplashFinishFragment.TAG)
.commit();
} else {
// fragment already set up from first onCreate after screen rotation
}
}
#Override
protected void onStart() {
// the activity becomes at least partially visible
mStarted = true;
super.onStart();
}
#Override
protected void onStop() {
// the activity is no longer visible
mStarted = false;
super.onStop();
}
public boolean isStarted2() {
// there is already hidden method isStarted() in the framework
// you can't use it and are not allowed to override it
return mStarted;
}
public static class SplashFinishFragment extends Fragment {
private static final String TAG = SplashFinishFragment.class.getSimpleName();
private static final int DELAY = 1000; // one second delay
private static final Handler mHandler = new Handler(); // one main thread anyway
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
if (getActivity() == null) {
// this should never happen, there is no activity, so no fragment
Log.e(TAG, "No activity!");
return;
}
SplashActivity a = (SplashActivity) getActivity();
if (a.isStarted2() || a.isChangingConfigurations()) {
// if activity is even partially visible or is rotating screen right now, continue
Intent i = new Intent(a, SettingsActivity.class);
a.startActivity(i);
}
// in any case close splash
a.finish();
}
};
public static SplashFinishFragment newInstance() {
return new SplashFinishFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// the countdown will continue (not reset) across screen rotations
setRetainInstance(true);
// try running the main activity after specified time
mHandler.postDelayed(mRunnable, DELAY);
}
#Override
public void onDestroy() {
// if the fragment gets destroyed (e.g. activity closes) do not launch main activity
mHandler.removeCallbacks(mRunnable);
super.onDestroy();
}
}
}
This was tested on a virtual Galaxy S2. It works when Home or Back button is pressed. It doesn't work when Recent Apps button is pressed. I don't know your use case but personally I would expect the app to continue launching while I browse recent apps.
What I would like to achieve is to stop the music when I go to my 2nd activity from my main activity (this works and the music does stop) But when I press the back button to go back to the main activity the music doesn't seem to start again. How can I make it to start again or if possible pause to music when going to the 2nd activity and resume when going back to the main activity.
Here is my code where the music stops when going to the next activity but doesn't play when going back to the main activity:
public class MainActivity extends Activity implements OnClickListener{
public static MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.music_a);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
player.stop();
}
});
}
protected void onPause() {
if (this.isFinishing()){
player.stop();
Toast.makeText(MainActivity.this, "BYE", Toast.LENGTH_LONG).show();
}
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
player.stop();
}
else {
}
}
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And here is my 2nd activity (do I need to put something here as well?)
public class SecondActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
}
}
Thanks
You have to call onResume on your First Activity to continue playing music
#Override
protected void onPause() {
super.onPause();
// stop the music
}
#Override
protected void onResume() {
super.onResume();
// play the music here
}
just remove your code to play from oncreate and start playing song in onResume
try {
if (player != null) {
player.start();
} else {
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.meintenu);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edit:
write this in your button click
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
player.stop();
player.release();
player=null;
pause Your music when you go to next activity and get the current position of the music
homeMusic.pause();
position=homeMusic.getCurrentPosition();
then add onRestart method,
#Override
protected void onRestart() {
super.onRestart();
homeMusic.seekTo(position);
homeMusic.start();
homeMusic.setLooping(true);
}
I have a sound on my app and when I play it and then press the home button, the app keeps running at the background ( I know it because the song keeps going.. ) How can I stop the app and the music?
here's my music code:
SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
int iTmp = sp.load(getBaseContext(), R.raw.windows_8_notify, 1);
sp.play(iTmp, 1, 1, 0, 0, 1);
MediaPlayer mPlayer = MediaPlayer.create(getBaseContext(), R.raw.windows_8_notify);
mPlayer.start();
mPlayer.setLooping(true);
Button btn_show = (Button) findViewById(R.id.show_popup);
btn_show.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (p != null)
showPopup(FirstActivity.this, p);
} }); }
In your Main Activity just override the onPause method, if you want to restart the music when you re-enter the app, the logic should go into your onResume method.
http://developer.android.com/reference/android/app/Activity.html for more info on the activity class that you must extend to create your android app.
class myActivity extends Activity {
#Override
public onCreate(Bundle savedInstanceState) {
// setup your app here
}
#Override
protected void onPause() {
// stop or pause your music here
// other "clean up"
}
#Override
protected void onResume() {
// app is now to the forground set things back up that might have been removed in onPause
}
}
stop the player inside the onStop activity callback method
#Override
protected void onStop() {
super.onStop();
if(mPlayer!=null && mPlayer.isPlaying())
mPlayer.stop();
}
I'm having a bit of a trouble,, here's the gen. idea,, I have created an app a simple game-like application.. however the problem is when I try to click the button in the title screen it doesn't play the click sound.. can anyone please help me.. here's the code for my sound
public class Effects extends Activity implements MediaPlayer.OnCompletionListener {
Button mPlay;
MediaPlayer mPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlay = (Button)findViewById(R.id.btnStart);
mPlay.setOnClickListener(playListener);
setContentView(R.layout.activity_main);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mPlayer != null) {
mPlayer.release();
}
}
private View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer == null) {
try {
mPlayer = MediaPlayer.create(Effects.this, R.raw.button11);
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
} else {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
};
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
}
and here's my code for the main java that I want the sound to be played when I clicked this button
public class Main extends Activity implements OnClickListener
{
Button about;
Button Quit;
Button start;
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
setContentView(R.layout.activity_main);
about = (Button)findViewById(R.id.btnAbout);
about.setOnClickListener(this);
Quit = (Button)findViewById(R.id.btnQuit);
Quit.setOnClickListener(this);
start = (Button)findViewById(R.id.btnStart);
start.setOnClickListener(this);
}
public void onClick(View argo)
{
if(argo.getId()==R.id.btnAbout)
{
Intent i = new Intent(this,About.class);
this.startActivity(i);
}
if(argo.getId()==R.id.btnQuit)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
if(argo.getId()==R.id.btnStart)
{
Intent start = new Intent(this,Howto.class);
this.startActivity(start);
Intent svc=new Intent(this,Effects.class);
startService(svc);
}
}
}
Use SoundPool to play your sounds: http://developer.android.com/reference/android/media/SoundPool.html you should init sounds in your onCreate() and then play them back in onClick()
And instead of doing thousands of pointless if(argo.getId()==R.id.btnQuit) (you should at least use else) get familiar with switch/case syntax)
I have my main Activity, it starts with a custom SurfaceView called DrawView being set by setContentView. The Main Activity (Draw) has the following method within it
public void launchCutScene(int scene) {
Intent intent = new Intent(Draw.this, CutScene.class);
startActivityForResult(intent, 0);
}
if I call this method directly after setContentView the new Activity CutScene loads properly. CutScene is as follows
public class CutScene extends Activity implements OnCompletionListener, OnPreparedListener{
String pathToFile = "";
VideoView videoPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pathToFile = "EM Math/" + "st.mp4";
setContentView(R.layout.main);
File root = Environment.getExternalStorageDirectory();
videoPlayer = (VideoView) findViewById(R.id.myvideoview);
videoPlayer.setOnPreparedListener(this);
videoPlayer.setOnCompletionListener(this);
videoPlayer.setKeepScreenOn(true);
videoPlayer.setVideoPath(root + "/" + pathToFile);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onPrepared(MediaPlayer vp) {
videoPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
finish();
}
#Override
public boolean onTouchEvent (MotionEvent ev){
if(ev.getAction() == MotionEvent.ACTION_DOWN){
if(videoPlayer.isPlaying()){
videoPlayer.pause();
} else {
videoPlayer.start();
}
return true;
} else {
return false;
}
}
}
However, if within DrawView I call draw.launchCutScene(0) then the activity still comes up, but the video glitches, it either stays as a black screen and you have to press back to make the activity crash, in which case it will bring up the first activity. Or it will play the sound only but multiple times and un-synced. Either way after it crashes if a launchCutScene call is done again within the DrawView class the video now works fine.
Why is this happening? does anybody understand what I need to do?
Okay, Finely fixed the error!
All I had to do was set my threads runnable boolean to false, then call the activity. Once activity closes my program reinitiates the thread, and everything work hunkydorry now!!!!... So if your getting this Video Bug with your Video Views it's probably because you are running a thread in the background!