How to get data from other activity in android?

后端 未结 5 1104
-上瘾入骨i
-上瘾入骨i 2020-12-31 19:47

I have two activities such as Activity A and B and I\'m trying to pass two different strings from A to B using Bundle and startActivity(inten

5条回答
  •  醉梦人生
    2020-12-31 20:44

    Here's another way to pass data between Activities. This is just an example from a tutorial I was following. I have a splash screen that runs for 5 seconds and then it would kill the sound clip from:

    @Override
    protected void onPause() {
        super.onPause();
        ourSong.release();
    }
    

    I decided I wanted the sound clip to continue playing into the next activity while still being able to kill/release it from there, so I made the sound clip, MediaPlayer object, public and static, similar to how out in System.out is a public static object. Being new to Android dev but not new to Java dev, I did it this way.

    import android.app.Activity;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    
    public class Splash extends Activity {
    
        public static MediaPlayer ourSong; // <----- Created the object to be shared
                                            // this way
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.splash);
            ourSong = MediaPlayer.create(Splash.this, R.raw.dubstep);
            ourSong.start();
            Thread timer = new Thread() {
                public void run() {
                    try {
                        sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        Intent openStartingPoint = new Intent(
                                "expectusafterlun.ch.androidtutorial.MENU");
                        startActivity(openStartingPoint);
                    }
                }
            };
            timer.start();
        }
    }
    

    Then from the next activity, or any other activity, I could access that MediaPlayer object.

    public class Menu extends ListActivity {
    
        String activities[] = { "Count", "TextPlay", "Email", "Camera", "example4",
                "example5", "example6" };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setListAdapter(new ArrayAdapter(Menu.this,
                    android.R.layout.simple_expandable_list_item_1, activities));
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            Splash.ourSong.release(); // <----- Accessing data from another Activity
                                        // here
        }
    
    }
    

提交回复
热议问题