Example usage for android.media MediaPlayer MediaPlayer

List of usage examples for android.media MediaPlayer MediaPlayer

Introduction

In this page you can find the example usage for android.media MediaPlayer MediaPlayer.

Prototype

public MediaPlayer() 

Source Link

Document

Default constructor.

Usage

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().setBackgroundDrawableResource(R.drawable.chat_bg);
    // this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    recipientStkid = getIntent().getExtras().getString("recipientStkid");
    chatRecipient = getIntent().getExtras().getString("chatRecipient");
    chatRecipientUrl = getIntent().getExtras().getString("chatRecipientUrl");
    senderToken = getIntent().getExtras().getString("senderToken");
    recipientToken = getIntent().getExtras().getString("recipientToken");
    noti = getIntent().getExtras().getBoolean("noti");
    message = getIntent().getExtras().getString("message");
    rows = getIntent().getExtras().getInt("rows");
    flagChatting = true;/*from  ww  w .  ja v a2s .  c om*/
    pref = PreferenceManager.getDefaultSharedPreferences(this);
    offerId = 0;
    offerStatus = 0;
    ws = new JsonWebService();
    dbHelper = new DBHelper(this);
    dialog = new ProgressDialog(this);
    listChatContact = new ArrayList<>();
    listChatContact = dbHelper.getChatContact();
    Log.i(" Chat Contact ", " " + listChatContact.size());
    metrics = this.getResources().getDisplayMetrics();
    //to change font
    faceSemi_bold = Typeface.createFromAsset(getAssets(), fontOSSemi_bold);
    Typeface faceLight = Typeface.createFromAsset(getAssets(), fontOSLight);
    faceRegular = Typeface.createFromAsset(getAssets(), fontOSRegular);

    imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited()) {
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }

    start = new Date();
    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
    timeSend = oFormat.format(start);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);

    layoutTalk = (LinearLayout) findViewById(R.id.layoutTalk);
    txtUserName = (TextView) findViewById(R.id.txtChatName);
    edTxtMsg = (EditText) findViewById(R.id.edTxtMsg);
    imgViewProfile = (ImageView) findViewById(R.id.imgViewChat);
    imgViewAddCon = (ImageView) findViewById(R.id.imgAddContact);
    lv = (ListView) findViewById(R.id.listView1);
    layoutLabel = (LinearLayout) findViewById(R.id.layoutLabel);
    txtLabel1 = (TextView) findViewById(R.id.txtLabel1);
    txtLabel2 = (TextView) findViewById(R.id.txtLabel2);
    txtLabel3 = (TextView) findViewById(R.id.txtLabel3);
    txtLabel2.setText(" " + chatRecipient + " ");
    txtLabel1.setTypeface(faceLight);
    txtLabel2.setTypeface(faceRegular);
    txtLabel3.setTypeface(faceLight);

    for (ChatContact contact : listChatContact) {
        if (contact.getContactId().equals(recipientStkid)) {
            imgViewAddCon.setVisibility(View.INVISIBLE);
            layoutLabel.setVisibility(View.GONE);
            break;
        }
    }
    Log.i(TAG, " come back again");
    adapter = new ChatArrayAdapter(this, R.layout.chatting_listview, faceSemi_bold, faceRegular, recipientStkid,
            senderToken, recipientToken);
    lv.setAdapter(adapter);
    // adapter.add(new StikyChat(chatRecipientUrl, "Hello", false, "12.10.2015", "12.1.2014"));

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    // BEGIN_INCLUDE (change_colors)
    // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
    swipeRefreshLayout.setColorScheme(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3,
            R.color.swipe_color_4);
    limitMsg = 7;
    // END_INCLUDE (change_colors)
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.i(" Refresh Layout ", "onRefresh called from SwipeRefreshLayout");
            if (limitMsg < rows) {
                Log.i("Limit Message ", " " + limitMsg);
                limitMsg *= 2;
                fetchRecords();
            } else if ((!(rows <= 7)) && limitMsg > rows && (limitMsg - rows < 7)) {
                fetchRecords();
            } else {
                Log.i("No data ", "to refresh");
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getApplicationContext(), "No data to refresh!", Toast.LENGTH_SHORT).show();
            }
            // initiateRefresh();
        }
    });

    LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout headerLayout = (LinearLayout) findViewById(R.id.header);
    View header = inflator.inflate(R.layout.header, null);

    TextView textView = (TextView) header.findViewById(R.id.textView1);
    textView.setText("StikyChat");
    textView.setTypeface(faceSemi_bold);
    textView.setVisibility(View.VISIBLE);
    headerLayout.addView(header);
    LinearLayout layoutRight = (LinearLayout) header.findViewById(R.id.layoutRight);
    layoutRight.setVisibility(View.GONE);

    txtUserName.setText(chatRecipient);
    Log.i(TAG, "Activity Name " + txtUserName.getText().toString());
    txtUserName.setTypeface(faceSemi_bold);

    String url = "";

    Log.i(TAG, " ^^^ " + chatRecipientUrl + " ");
    if (chatRecipientUrl != null) {
        if (chatRecipientUrl.contains("http")) {
            url = chatRecipientUrl;
        } else if (chatRecipientUrl != "null") {
            url = this.getResources().getString(R.string.url) + "/" + chatRecipientUrl;
        }
    }
    addAndroidUniversalImageLoader(imgViewProfile, url);
    //        if (noti && (!message.equals(""))) {
    //            adapter.add(new StikyChat(chatRecipientUrl, message, true, timeSend, ""));
    //            lv.smoothScrollToPosition(adapter.getCount() - 1);
    //        }

    //to show history chats between two users(sender & recipient)
    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat2 = new SimpleDateFormat("dd MMM HH:mm");
    listHistory = dbHelper.getStikyChat();
    if (listHistory.size() > 0) {
        Collections.reverse(listHistory);
        for (final StikyChatTb chatTb : listHistory) {
            String getDate = chatTb.getSendDate();
            String durationStr = null;
            String fromStikyBee = chatTb.getSender();
            try {
                final String createDate = dateFormat2.format(dateFormat.parse(getDate));
                if (chatTb.getFileName().contains("voice")) {
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);

                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    // Log.i(TAG, "Duration Srt " + durationStr);
                }
                if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                    //String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    // Log.i(TAG, " Offer Id " + chatTb.getOfferId() + " Price " + chatTb.getPrice() + " Name " + chatTb.getName());
                    //first false = right, second false = Offer
                    //  Log.i(TAG, " Duration " + chatTb.getRate() + " File Name " + chatTb.getFileName());
                    if (!chatTb.getFileName().contains("voice")) {
                        Log.i(TAG, " Voice is not ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        Log.i(TAG, " Voice is ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                } else {
                    /* Bitmap bmImg = BitmapFactory.decodeFile(getResources().getString(R.string.url) + "/" + chatTb.getFileName());
                     Bitmap resBm = getResizedBitmap(bmImg, 500);*/
                    // String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    if (!chatTb.getFileName().contains("voice")) {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                }
                lv.smoothScrollToPosition(adapter.getCount() - 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            fileNameGCM = sharedPreferences.getString("fileName", "");
            messageGCM = sharedPreferences.getString("message", "");
            offerIdGCM = sharedPreferences.getInt("offerId", 0);
            offerStatusGCM = sharedPreferences.getInt("offerStatus", 0);
            priceGCM = sharedPreferences.getString("price", "");
            rateGCM = sharedPreferences.getString("rate", "");
            nameGCM = sharedPreferences.getString("name", "");
            recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
            recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
            recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
            recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
            senderTokenGCM = sharedPreferences.getString("senderToken", "");

            Log.i(TAG, " FileName GCM " + fileNameGCM + " " + " Name Rate Price &&&&& *** " + messageGCM + " "
                    + priceGCM + " " + rateGCM);
            if (firstConnect) {
                if (recipientStkidGCM.trim() == recipientStkid.trim()
                        || recipientStkidGCM.equals(recipientStkid)) {
                    MyGcmListenerService.flagSendNoti = false;
                    Log.i(TAG, " " + message);
                    // (1) get today's date
                    start = new Date();
                    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
                    timeSend = oFormat.format(start);

                    Log.i(TAG, "First connect " + firstConnect);
                    Log.i(TAG, " File Name GCMMMMMM " + fileNameGCM);
                    /*if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    oriFName = saveFileAndImage(fileNameGCM);
                    }*/
                    /*if (fileNameGCM.contains("voice")) {
                    String durationStr;
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + fileNameGCM;
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                            
                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);
                            
                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, durationStr, null, oriFName);
                    adapter.add(stikyChat);
                    } else {*/
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend,
                            fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, nameGCM, null,
                            oriFName);
                    adapter.add(stikyChat);
                    //  }
                    Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                    Log.i(TAG, "User " + txtUserName.getText().toString());

                    adapter.notifyDataSetChanged();
                    lv.setSelection(adapter.getCount() - 1);
                    new regTask2().execute("Obj ");
                } else {
                    /* if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    saveFileAndImage(fileNameGCM);
                     }*/
                    Log.i(TAG, "..." + recipientStkidGCM.trim());
                    Log.i(TAG, "&&&" + recipientStkid.trim());
                    Log.i(TAG, "else casee");
                    //notificaton send
                    flagNotifi = true;
                    new regTask2().execute("Notification");
                }
                firstConnect = false;
            }
            lv.setSelection(adapter.getCount() - 1);
        }
    };

    /*edTxtMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
      Toast.makeText(getBaseContext(),
                ((EditText) v).getId() + " has focus - " + hasFocus,
                Toast.LENGTH_LONG).show();
    }
    });*/
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    edTxtMsg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutTalk.setLayoutParams(params);
            layoutTalk.setGravity(Gravity.CENTER);
            flagRecord = false;
            /*getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
            );*/
            Toast.makeText(getBaseContext(), "Touch ...", Toast.LENGTH_LONG).show();
            return false;
        }
    });
}

From source file:com.example.android.supportv4.media.Playback.java

/**
 * Makes sure the media player exists and has been reset. This will create
 * the media player if needed, or reset the existing media player if one
 * already exists./*from   w  w  w. j a va 2  s .  co  m*/
 */
private void createMediaPlayerIfNeeded() {
    Log.d(TAG, "createMediaPlayerIfNeeded. needed? " + (mMediaPlayer == null));
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();

        // Make sure the media player will acquire a wake-lock while
        // playing. If we don't do that, the CPU might go to sleep while the
        // song is playing, causing playback to stop.
        mMediaPlayer.setWakeMode(mService.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing,
        // and when it's done playing:
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnSeekCompleteListener(this);
    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.appdevper.mediaplayer.app.LocalPlayback.java

/**
 * Makes sure the media player exists and has been reset. This will create
 * the media player if needed, or reset the existing media player if one
 * already exists./* w  ww .  jav  a 2  s  .c om*/
 */
private void createMediaPlayerIfNeeded() {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer == null));
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setWakeMode(mService.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnSeekCompleteListener(this);
    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.android.onemedia.playback.LocalRenderer.java

@Override
public void setNextContent(Bundle request) {
    String source = request.getString(RequestUtils.EXTRA_KEY_SOURCE);
    Map<String, String> headers = null; // request.mHeaders;

    // TODO support video

    if (DEBUG) {/*w  ww .j a v a  2 s  . c o  m*/
        Log.d(TAG, mDebugId + ": Setting next content. Have player? " + (mPlayer != null)
                + " have next player? " + (mNextPlayer != null));
    }

    if (mPlayer == null) {
        // The manager isn't being used to play anything, don't try to
        // set a next.
        return;
    }
    if (mNextPlayer != null) {
        // Before setting up the new one clear out the old one and release
        // it to ensure it doesn't play.
        mPlayer.setNextMediaPlayer(null);
        mNextPlayer.release();
        mNextPlayer = null;
        mNextContent = null;
    }
    if (source == null) {
        // If there's no new content we're done
        return;
    }
    final MediaPlayer newPlayer = new MediaPlayer();

    try {
        if (headers != null) {
            Uri sourceUri = Uri.parse(source);
            newPlayer.setDataSource(mContext, sourceUri, headers);
        } else {
            newPlayer.setDataSource(source);
        }
    } catch (Exception e) {
        newPlayer.release();
        // Don't return an error until we get to this item in playback
        return;
    }

    if (preparePlayer(newPlayer, false)) {
        mPlayer.setNextMediaPlayer(newPlayer);
        mNextPlayer = newPlayer;
        mNextContent = new PlayerContent(source, headers);
    }
}

From source file:com.example.android.mediabrowserservice.Playback.java

/**
 * Makes sure the media player exists and has been reset. This will create
 * the media player if needed, or reset the existing media player if one
 * already exists.//from w w w. ja  v  a2s.c  om
 */
private void createMediaPlayerIfNeeded() {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer == null));
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();

        // Make sure the media player will acquire a wake-lock while
        // playing. If we don't do that, the CPU might go to sleep while the
        // song is playing, causing playback to stop.
        mMediaPlayer.setWakeMode(mService.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing,
        // and when it's done playing:
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnSeekCompleteListener(this);
    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.google.dotorg.crisisresponse.translationcards.RecordingActivity.java

private void startListening() {
    recordButton.setBackgroundResource(R.drawable.button_record_disabled);
    listenButton.setBackgroundResource(R.drawable.button_listen_active);
    recordingStatus = RecordingStatus.LISTENING;
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {//from   ww w  . jav a  2  s .  co  m
        if (isAsset) {
            AssetFileDescriptor fd = getAssets().openFd(filename);
            mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            fd.close();
        } else {
            mediaPlayer.setDataSource(new FileInputStream(filename).getFD());
        }
        mediaPlayer.prepare();
    } catch (IOException e) {
        Log.d(TAG, "Error preparing audio.");
        throw new IllegalArgumentException(e);
        // TODO(nworden): something
    }
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            finishListening(mp);
        }
    });
    mediaPlayer.start();
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override/*from  w w  w .j  av a2 s  .c o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.d(LOG_TAG, "onCreate() : " + savedInstanceState);

    setContentView(R.layout.activity_jet_pack_elf);

    // App Invites
    mInvitesFragment = AppInvitesFragment.getInstance(this);

    // App Measurement
    mMeasurement = FirebaseAnalytics.getInstance(this);
    MeasurementManager.recordScreenView(mMeasurement, getString(R.string.analytics_screen_rocket));

    // [ANALYTICS SCREEN]: Rocket Sleigh
    AnalyticsManager.initializeAnalyticsTracker(this);
    AnalyticsManager.sendScreenView(R.string.analytics_screen_rocket);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        ImmersiveModeHelper.setImmersiveSticky(getWindow());
        ImmersiveModeHelper.installSystemUiVisibilityChangeListener(getWindow());
    }

    mIntroVideo = (VideoView) findViewById(R.id.intro_view);
    mIntroControl = findViewById(R.id.intro_control_view);
    if (savedInstanceState == null) {
        String path = "android.resource://" + getPackageName() + "/" + R.raw.jp_background;
        mBackgroundPlayer = new MediaPlayer();
        try {
            mBackgroundPlayer.setDataSource(this, Uri.parse(path));
            mBackgroundPlayer.setLooping(true);
            mBackgroundPlayer.prepare();
            mBackgroundPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        boolean nomovie = false;
        if (getIntent().getBooleanExtra("nomovie", false)) {
            nomovie = true;
        } else if (Build.MANUFACTURER.toUpperCase().contains("SAMSUNG")) {
            //                nomovie = true;
        }
        if (!nomovie) {
            mIntroControl.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    endIntro();
                }
            });
            path = "android.resource://" + getPackageName() + "/" + R.raw.intro_wipe;
            mIntroVideo.setVideoURI(Uri.parse(path));
            mIntroVideo.setOnCompletionListener(this);
            mIntroVideo.start();
            mMoviePlaying = true;
        } else {
            mIntroControl.setOnClickListener(null);
            mIntroControl.setVisibility(View.GONE);
            mIntroVideo.setVisibility(View.GONE);
        }
    } else {
        mIntroControl.setOnClickListener(null);
        mIntroControl.setVisibility(View.GONE);
        mIntroVideo.setVisibility(View.GONE);
    }

    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // For hit indication.

    mHandler = new Handler(); // Get the main UI handler for posting update events

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    Log.d(LOG_TAG, "Width: " + dm.widthPixels + " Height: " + dm.heightPixels + " Density: " + dm.density);

    mScreenHeight = dm.heightPixels;
    mScreenWidth = dm.widthPixels;
    mSlotWidth = mScreenWidth / SLOTS_PER_SCREEN;

    // Setup the random number generator
    mRandom = new Random();
    mRandom.setSeed(System.currentTimeMillis()); // This is ok.  We are not looking for cryptographically secure random here!

    mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // Setup the background/foreground
    mBackgroundLayout = (LinearLayout) findViewById(R.id.background_layout);
    mBackgroundScroll = (HorizontalScrollView) findViewById(R.id.background_scroll);
    mForegroundLayout = (LinearLayout) findViewById(R.id.foreground_layout);
    mForegroundScroll = (HorizontalScrollView) findViewById(R.id.foreground_scroll);

    mBackgrounds = new Bitmap[6];
    mBackgrounds2 = new Bitmap[6];
    mExitTransitions = new Bitmap[6];
    mEntryTransitions = new Bitmap[6];

    // Need to vertically scale background to fit the screen.  Checkthe image size
    // compared to screen size and scale appropriately.  We will also use the matrix to translate
    // as we move through the level.
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), BACKGROUNDS[0]);
    Log.d(LOG_TAG, "Bitmap Width: " + bmp.getWidth() + " Height: " + bmp.getHeight() + " Screen Width: "
            + dm.widthPixels + " Height: " + dm.heightPixels);
    mScaleY = (float) dm.heightPixels / (float) bmp.getHeight();
    mScaleX = (float) (dm.widthPixels * 2) / (float) bmp.getWidth(); // Ensure that a single bitmap is 2 screens worth of time.  (Stock xxhdpi image is 3840x1080)

    if ((mScaleX != 1.0f) || (mScaleY != 1.0f)) {
        Bitmap tmp = Bitmap.createScaledBitmap(bmp, mScreenWidth * 2, mScreenHeight, false);
        if (tmp != bmp) {
            bmp.recycle();
            bmp = tmp;
        }
    }
    BackgroundLoadTask.createTwoBitmaps(bmp, mBackgrounds, mBackgrounds2, 0);

    // Load the initial background view
    addNextImages(0);
    addNextImages(0);

    mWoodObstacles = new TreeMap<Integer, Bitmap>();
    mWoodObstacleList = new ArrayList<Integer>();
    mWoodObstacleIndex = 0;
    // We need the bitmaps, so we do pre-load here synchronously.
    initObstaclesAndPreLoad(WOOD_OBSTACLES, 3, mWoodObstacles, mWoodObstacleList);

    mCaveObstacles = new TreeMap<Integer, Bitmap>();
    mCaveObstacleList = new ArrayList<Integer>();
    mCaveObstacleIndex = 0;
    initObstacles(CAVE_OBSTACLES, 2, mCaveObstacleList);

    mFactoryObstacles = new TreeMap<Integer, Bitmap>();
    mFactoryObstacleList = new ArrayList<Integer>();
    mFactoryObstacleIndex = 0;
    initObstacles(FACTORY_OBSTACLES, 2, mFactoryObstacleList);

    // Setup the elf
    mElf = (ImageView) findViewById(R.id.elf_image);
    mThrust = (ImageView) findViewById(R.id.thrust_image);
    mElfLayout = (LinearLayout) findViewById(R.id.elf_container);
    loadElfImages();
    updateElf(false);
    // Elf should be the same height relative to the height of the screen on any platform.
    Matrix scaleMatrix = new Matrix();
    mElfScale = ((float) dm.heightPixels * 0.123f) / (float) mElfBitmap.getHeight(); // On a 1920x1080 xxhdpi screen, this makes the elf 133 pixels which is the height of the drawable.
    scaleMatrix.preScale(mElfScale, mElfScale);
    mElf.setImageMatrix(scaleMatrix);
    mThrust.setImageMatrix(scaleMatrix);
    mElfPosX = (dm.widthPixels * 15) / 100; // 15% Into the screen
    mElfPosY = (dm.heightPixels - ((float) mElfBitmap.getHeight() * mElfScale)) / 2; // About 1/2 way down.
    mElfVelX = (float) dm.widthPixels / 3000.0f; // We start at 3 seconds for a full screen to scroll.
    mGravityAccelY = (float) (2 * dm.heightPixels) / (float) Math.pow((1.2 * 1000.0), 2.0); // a = 2*d/t^2 Where d = height in pixels and t = 1.2 seconds
    mThrustAccelY = (float) (2 * dm.heightPixels) / (float) Math.pow((0.7 * 1000.0), 2.0); // a = 2*d/t^2 Where d = height in pixels and t = 0.7 seconds

    // Setup the control view
    mControlView = findViewById(R.id.control_view);
    mGestureDetector = new GestureDetector(this, this);
    mGestureDetector.setIsLongpressEnabled(true);
    mGestureDetector.setOnDoubleTapListener(this);

    mScoreLabel = getString(R.string.score);
    mScoreText = (TextView) findViewById(R.id.score_text);
    mScoreText.setText("0");

    mPlayPauseButton = (ImageView) findViewById(R.id.play_pause_button);
    mExit = (ImageView) findViewById(R.id.exit);

    // Is Tv?
    mIsTv = TvUtil.isTv(this);
    if (mIsTv) {
        mScoreText.setText(mScoreLabel + ": 0");
        mPlayPauseButton.setVisibility(View.GONE);
        mExit.setVisibility(View.GONE);
        // move scoreLayout position to the Top-Right corner.
        View scoreLayout = findViewById(R.id.score_layout);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) scoreLayout.getLayoutParams();
        params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        params.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

        final int marginTop = getResources().getDimensionPixelOffset(R.dimen.overscan_margin_top);
        final int marginLeft = getResources().getDimensionPixelOffset(R.dimen.overscan_margin_left);

        params.setMargins(marginLeft, marginTop, 0, 0);
        scoreLayout.setLayoutParams(params);
        scoreLayout.setBackground(null);
        scoreLayout.findViewById(R.id.score_text_seperator).setVisibility(View.GONE);
    } else {
        mPlayPauseButton.setEnabled(false);
        mPlayPauseButton.setOnClickListener(this);
        mExit.setOnClickListener(this);
    }

    mBigPlayButtonLayout = findViewById(R.id.big_play_button_layout);
    mBigPlayButtonLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // No interaction with the screen below this one.
            return true;
        }
    });
    mBigPlayButton = (ImageButton) findViewById(R.id.big_play_button);
    mBigPlayButton.setOnClickListener(this);

    // For showing points when getting presents.
    mPlus100 = (ImageView) findViewById(R.id.plus_100);
    m100Anim = new AlphaAnimation(1.0f, 0.0f);
    m100Anim.setDuration(1000);
    m100Anim.setFillBefore(true);
    m100Anim.setFillAfter(true);
    mPlus500 = (ImageView) findViewById(R.id.plus_500);
    m500Anim = new AlphaAnimation(1.0f, 0.0f);
    m500Anim.setDuration(1000);
    m500Anim.setFillBefore(true);
    m500Anim.setFillAfter(true);

    // Get the obstacle layouts ready.  No obstacles on the first screen of a level.
    // Prime with a screen full of obstacles.
    mObstacleLayout = (LinearLayout) findViewById(R.id.obstacles_layout);
    mObstacleScroll = (HorizontalScrollView) findViewById(R.id.obstacles_scroll);

    // Initialize the present bitmaps.  These are used repeatedly so we keep them loaded.
    mGiftBoxes = new Bitmap[GIFT_BOXES.length];
    for (int i = 0; i < GIFT_BOXES.length; i++) {
        mGiftBoxes[i] = BitmapFactory.decodeResource(getResources(), GIFT_BOXES[i]);
    }

    // Add starting obstacles.  First screen has presents.  Next 3 get obstacles.
    addFirstScreenPresents();
    //        addFinalPresentRun();  // This adds 2 screens of presents
    //        addNextObstacles(0, 1);
    addNextObstacles(0, 3);

    // Setup the sound pool
    mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
    mSoundPool.setOnLoadCompleteListener(this);
    mCrashSound1 = mSoundPool.load(this, R.raw.jp_crash_1, 1);
    mCrashSound2 = mSoundPool.load(this, R.raw.jp_crash_2, 1);
    mCrashSound3 = mSoundPool.load(this, R.raw.jp_crash_3, 1);
    mGameOverSound = mSoundPool.load(this, R.raw.jp_game_over, 1);
    mJetThrustSound = mSoundPool.load(this, R.raw.jp_jet_thrust, 1);
    mLevelUpSound = mSoundPool.load(this, R.raw.jp_level_up, 1);
    mScoreBigSound = mSoundPool.load(this, R.raw.jp_score_big, 1);
    mScoreSmallSound = mSoundPool.load(this, R.raw.jp_score_small, 1);
    mJetThrustStream = 0;

    if (!mMoviePlaying) {
        doCountdown();
    }
}

From source file:se.droidgiro.scanner.CaptureActivity.java

/**
 * Creates the beep MediaPlayer in advance so that the sound can be
 * triggered with the least latency possible.
 *//*  w ww.j  a  v a 2 s . com*/
private void initBeepSound() {
    if (playBeep && mediaPlayer == null) {
        // The volume on STREAM_SYSTEM is not adjustable, and users found it
        // too loud,
        // so we now play on the music stream.
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnCompletionListener(beepListener);

        AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
            file.close();
            mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
            mediaPlayer.prepare();
        } catch (IOException e) {
            mediaPlayer = null;
        }
    }
}

From source file:com.example.android.AudioArchive.playback.LocalPlayback.java

/**
 * Makes sure the media player exists and has been reset. This will create
 * the media player if needed, or reset the existing media player if one
 * already exists./*from  w w w  .  j  a v a 2  s  . c  o m*/
 */
private void createMediaPlayerIfNeeded() {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer == null));
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();

        // Make sure the media player will acquire a wake-lock while
        // playing. If we don't do that, the CPU might go to sleep while the
        // song is playing, causing playback to stop.
        mMediaPlayer.setWakeMode(mContext.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing,
        // and when it's done playing:
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnSeekCompleteListener(this);
    } else {
        mMediaPlayer.reset();
    }
}