Please Can Someone help me to get hands on the error in this source code for 2 subjects gpa calculator as it is giving me Force Close
Here`s the source code
"
package com.gado.e001;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
RadioButton gradea1, gradeb1, gradec1, graded1, gradea2, gradeb2, gradec2,
graded2;
EditText hours1, hours2;
Button calc;
float fgrade1, fgrade2, fhours1, fhours2;
float Result = fgrade1 + fgrade2 + fhours1 + fhours2;
public void Identify() {
gradea1 = (RadioButton) findViewById(R.id.radioButton1);
gradeb1 = (RadioButton) findViewById(R.id.radioButton2);
gradec1 = (RadioButton) findViewById(R.id.radioButton3);
graded1 = (RadioButton) findViewById(R.id.radioButton4);
gradea2 = (RadioButton) findViewById(R.id.radioButton5);
gradeb2 = (RadioButton) findViewById(R.id.radioButton6);
gradec2 = (RadioButton) findViewById(R.id.radioButton7);
graded2 = (RadioButton) findViewById(R.id.radioButton8);
hours1 = (EditText) findViewById(R.id.editText1);
hours2 = (EditText) findViewById(R.id.editText2);
calc = (Button) findViewById(R.id.button1);
}
public void getting() {
gradea1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade1 = 4f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradeb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade1 = 3f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradec1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade1 = 2f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
graded1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade1 = 1f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradea2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade2 = 4f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradeb2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade2 = 3f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradec2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade2 = 2f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
graded2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade2 = 1f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
fhours1 = Float.parseFloat(hours1.getText().toString());
fhours2 = Float.parseFloat(hours2.getText().toString());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Identify();
getting();
Toast.makeText(getBaseContext(), "" + Result, Toast.LENGTH_LONG)
.show();
}
});
}
}
"
Please Help Me
You might be better off asking this question on Stackoverflow.
Run your app with your phone connected to your PC and Eclipse running, this way Eclipse will show you the error so you can tell us what is it.
Related
Hello,
I have source code from an appli running on android 3.2 with a WAMP Server and WowZa Server on my desktop. I have to make it accept the HLS (Http Live Streaming). I saw on the web that the Vitamio Library can do that so i used it. I know that natively, android 3.0+ do it well but i do not succeeded make it work successfully.
The player is successfully displayed but no video starts..
After a reboot of my router (because my server didn't answer), the player crash each time.
Somestimes yes, sometimes no, i have some logs, they are as attachment.
I think a buffer problem...
I think I have to implement this method (at the end of my code) but i know what type in it.
public void onBufferingUpdate(MediaPlayer mPlayer, int percent)
IT WORKS VERY WELL WITH .MP4
Here's my code from the Player Activity :
Code:
package fr.niji.broadpeak.activity;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
/*import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;*/
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.MediaPlayer.OnBufferingUpdateListener;
import io.vov.vitamio.MediaPlayer.OnCompletionListener;
import io.vov.vitamio.MediaPlayer.OnErrorListener;
import io.vov.vitamio.MediaPlayer.OnPreparedListener;
import io.vov.vitamio.MediaPlayer.OnVideoSizeChangedListener;
import io.vov.vitamio.VitamioInstaller;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
//import io.vov.vitamio.widget.VideoView;
import android.view.View;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import fr.niji.broadpeak.R;
import fr.niji.broadpeak.dataproxy.service.BroadpeakDataManager;
import fr.niji.broadpeak.dataproxy.webservice.getsessionurl.GetSessionUrl;
import fr.niji.broadpeak.util.Config;
import fr.niji.broadpeak.util.Resources;
import fr.niji.broadpeak.util.TimeUtils;
import fr.niji.lib.dataproxy.model.ResponseBusinessObject;
import fr.niji.lib.dataproxy.service.DataManager.OnDataListener;
import fr.niji.lib.dataproxy.service.model.BusinessResponse;
public class BroadpeakDemoPlayer extends Activity implements OnClickListener, OnPreparedListener, OnErrorListener,
OnVideoSizeChangedListener, Callback, OnSeekBarChangeListener, OnCompletionListener, OnDataListener, OnBufferingUpdateListener{
private static final String LOG_TAG = BroadpeakDemoPlayer.class.getSimpleName();
public static final String PLAYER_FILE_PATH = "playerLivePath";
public static final String PLAYER_FILE_ID = "playerFileId";
public static final String PLAYER_TYPE = "playerType";
public static final String PLAYER_RESUME_POSITION = "playerResumePosition";
public static final int TYPE_VOD_CONNECTED = 1;
public static final int TYPE_VOD_EMULATED = 2;
public static final int TYPE_LIVE_CONNECTED = 3;
public static final int TYPE_LIVE_EMULATED = 4;
private static final int DELTA_RW_FW = 5000;
private static final int DELTA_LIVE = 30000;
private static final int PROGRESS_BAR_UPDATE_DELAY = 1500;
private SurfaceView mSurfaceView;
//private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private MediaPlayer mMediaPlayer;
//VitamioInstaller vitamioInstaller;
private int mPlayerType;
private int mCurrentBufferPercentage;
private String mFilePath;
private String mFileId;
private int mResumePosition;
int percentBuffer;
private Toast mToast;
private WakeLock mWakeLock;
private int mTerminalType;
private String mUserId;
private long mLastPosition;
private RelativeLayout mLayoutControls;
private boolean mIsLayoutControlsVisible = true;
private SeekBar mSeekBar;
private TextView mTextViewCurrentTime;
private TextView mTextViewFullTime;
private ImageButton mButtonStartOver;
private ImageButton mButtonPlay;
private ImageButton mButtonPause;
private ImageButton mButtonRewind;
private ImageButton mButtonForward;
private ImageButton mButtonLive;
private boolean mIsButtonLiveEnabled = true;
private boolean mIsVideoReadyToBePlayed = false;
private boolean mIsVideoDimensionsKnown = false;
private int mVideoHeight = 0;
private int mVideoWidth = 0;
private long mVideoLength = -1;
private int mRequestId = -1;
private Runnable mRunnableProgressBarUpdate;
private Handler mHandler = new Handler();
private BroadpeakDataManager mDataManager;
private String mErrorGettingVideo;
private String mErrorPlayingVideo;
@Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
Intent intent = getIntent();
mDataManager = BroadpeakDataManager.getInstance(this);
mErrorGettingVideo = getString(R.string.error_getting_video_url);
mErrorPlayingVideo = getString(R.string.error_playing_video);
if (intent != null) {
mPlayerType = intent.getIntExtra(PLAYER_TYPE, 0);
mFilePath = intent.getStringExtra(PLAYER_FILE_PATH);
mFileId = intent.getStringExtra(PLAYER_FILE_ID);
if (Config.SHOW_LOG) {
Log.d(LOG_TAG, "mFilePath: " + mFilePath);
Log.d(LOG_TAG, "mFileId: " + mFileId);
}
mResumePosition = intent.getIntExtra(PLAYER_RESUME_POSITION, 0);
// must retrieve url ?
if (mFilePath == null || mFilePath.length() == 0) {
try {
mRequestId = mDataManager.getSessionUrl(this, mFileId, Resources.getInstance().mUserId);
mDataManager.addOnDataListener(mRequestId, this);
} catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
setContentView(R.layout.player);
// Decalage a 30s pour le live emulated
if (mPlayerType == TYPE_LIVE_EMULATED) {
mResumePosition = Config.LIVE_DEFAULT_OFFSET;
}
// Player management
//mSurfaceView = (SurfaceView) findViewById(R.id.surface_live);
mSurfaceView = (SurfaceView) findViewById(R.id.surface_live);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// Controls management
mLayoutControls = (RelativeLayout) findViewById(R.id.player_controls);
mLayoutControls.setClickable(true);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mSeekBar.setOnSeekBarChangeListener(this);
mTextViewCurrentTime = (TextView) findViewById(R.id.textview_current_time);
mTextViewFullTime = (TextView) findViewById(R.id.textview_full_time);
mButtonStartOver = (ImageButton) findViewById(R.id.btn_startover);
mButtonStartOver.setOnClickListener(this);
mButtonPlay = (ImageButton) findViewById(R.id.btn_play);
mButtonPlay.setOnClickListener(this);
mButtonPause = (ImageButton) findViewById(R.id.btn_pause);
mButtonPause.setOnClickListener(this);
mButtonRewind = (ImageButton) findViewById(R.id.btn_rw);
mButtonRewind.setOnClickListener(this);
mButtonForward = (ImageButton) findViewById(R.id.btn_fw);
mButtonForward.setOnClickListener(this);
mButtonLive = (ImageButton) findViewById(R.id.btn_live);
mButtonLive.setOnClickListener(this);
Resources resources = Resources.getInstance();
mTerminalType = resources.mTerminalType;
mUserId = resources.mUserId;
// Player type management
switch (mPlayerType) {
case TYPE_LIVE_CONNECTED:
mLayoutControls.setVisibility(View.GONE);
mIsLayoutControlsVisible = false;
break;
case TYPE_LIVE_EMULATED:
mSeekBar.setVisibility(View.GONE);
mTextViewCurrentTime.setVisibility(View.GONE);
mTextViewFullTime.setVisibility(View.GONE);
break;
case TYPE_VOD_CONNECTED:
mButtonStartOver.setVisibility(View.GONE);
mButtonLive.setVisibility(View.GONE);
break;
case TYPE_VOD_EMULATED:
mButtonStartOver.setVisibility(View.GONE);
mButtonLive.setVisibility(View.GONE);
break;
}
mRunnableProgressBarUpdate = new Runnable() {
public void run() {
mHandler.removeCallbacks(mRunnableProgressBarUpdate);
int progress = -1;
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
if (mVideoLength > 0) {
final long currentPosition = mMediaPlayer.getCurrentPosition();
progress = (int) Math.floor(currentPosition / (float) mVideoLength * 100);
mSeekBar.setProgress(progress);
mTextViewCurrentTime.setText(TimeUtils.formatDuration(currentPosition / 1000));
} else {
progress = 0;
mSeekBar.setProgress(progress);
mTextViewCurrentTime.setText("");
}
}
mHandler.postDelayed(mRunnableProgressBarUpdate, PROGRESS_BAR_UPDATE_DELAY);
}
};
}
@Override
protected void onResume() {
super.onResume();
acquireWakeLock();
}
@Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
releaseWakeLock();
}
@Override
protected void onStop() {
super.onStop();
if (mPlayerType == TYPE_VOD_CONNECTED) {
try {
BroadpeakDataManager.getInstance(this).retrieveSetLastPlay(BroadpeakDataManager.TYPE_NETWORK, null,
mTerminalType, mUserId, mFileId, mLastPosition, -1);
} catch (UnsupportedEncodingException e) {
Log.e(LOG_TAG, "Error while calling setLastPlay", e);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
public void surfaceChanged(final SurfaceHolder holder, final int format, final int width, final int height) {
Log.d(LOG_TAG, "surfaceChanged called");
}
public void surfaceDestroyed(final SurfaceHolder holder) {
Log.d(LOG_TAG, "surfaceDestroyed called");
}
public void surfaceCreated(final SurfaceHolder holder) {
Log.d(LOG_TAG, "surfaceCreated called");
if (mFilePath != null) {
playVideo();
}
}
public void onClick(final View view) {
if (view == mSurfaceView) {
if (mPlayerType != TYPE_LIVE_CONNECTED) {
mLayoutControls.setVisibility(mIsLayoutControlsVisible ? View.GONE : View.VISIBLE);
mIsLayoutControlsVisible = !mIsLayoutControlsVisible;
}
} else if (view == mButtonPlay) {
pressPlayButton();
} else if (view == mButtonPause) {
pressPauseButton();
} else if (view == mButtonRewind) {
if (mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED) {
mButtonLive.setEnabled(true);
mButtonForward.setEnabled(true);
mIsButtonLiveEnabled = true;
}
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition() - DELTA_RW_FW);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
} else if (view == mButtonForward) {
if (mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED) {
mButtonStartOver.setEnabled(true);
}
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition() + DELTA_RW_FW);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
} else if (view == mButtonLive) {
mButtonForward.setEnabled(false);
mButtonLive.setEnabled(false);
mIsButtonLiveEnabled = false;
mButtonStartOver.setEnabled(true);
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition() + DELTA_LIVE);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
} else if (view == mButtonStartOver) {
mButtonLive.setEnabled(true);
mButtonForward.setEnabled(true);
mIsButtonLiveEnabled = true;
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.seekTo(0);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
}
}
private void pressPauseButton() {
mButtonPlay.setVisibility(View.VISIBLE);
mButtonPause.setVisibility(View.GONE);
mButtonForward.setEnabled(false);
mButtonRewind.setEnabled(false);
if (mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED) {
mButtonLive.setEnabled(false);
mButtonStartOver.setEnabled(false);
}
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
}
private void pressPlayButton() {
mButtonPlay.setVisibility(View.GONE);
mButtonPause.setVisibility(View.VISIBLE);
if (mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED) {
if (mIsButtonLiveEnabled) {
mButtonLive.setEnabled(true);
mButtonForward.setEnabled(true);
}
mButtonRewind.setEnabled(true);
mButtonStartOver.setEnabled(true);
} else {
mButtonRewind.setEnabled(true);
mButtonForward.setEnabled(true);
}
try {
if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
}
private void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
/*mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(mFilePath);
mMediaPlayer.setLooping(mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.prepare();
mMediaPlayer.seekTo(mResumePosition);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);*/
mMediaPlayer = new MediaPlayer(this);
mMediaPlayer.setDataSource(mFilePath);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.prepare();
mMediaPlayer.seekTo(mResumePosition);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
//mMediaPlayer.setAudioTrack(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
} catch (Exception e) {
Log.e(LOG_TAG, "error: " + e.getMessage(), e);
showErrorMessage(mErrorPlayingVideo);
// Toast.makeText(this, "Impossible de jouer la vidéo",
// 5000).show();
}
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mLastPosition = mMediaPlayer.getCurrentPosition() / 1000;
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mVideoLength = -1;
mIsVideoReadyToBePlayed = false;
mIsVideoDimensionsKnown = false;
mHandler.removeCallbacks(mRunnableProgressBarUpdate);
}
private void acquireWakeLock() {
PowerManager.WakeLock wl = mWakeLock;
if (wl == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG);
}
if (!wl.isHeld()) {
wl.acquire();
Log.d(LOG_TAG, "acquire wakelock");
}
}
private void releaseWakeLock() {
PowerManager.WakeLock wl = mWakeLock;
if (wl != null) {
if (wl.isHeld()) {
wl.release();
Log.d(LOG_TAG, "release wakelock");
}
}
}
private void showErrorMessage(final String string) {
if (mToast != null) {
mToast.cancel();
mToast.setText(string);
} else {
mToast = Toast.makeText(this, string, Toast.LENGTH_LONG);
}
mToast.show();
}
private void startVideoPlayback() {
Log.d(LOG_TAG, "startReading: width " + mVideoWidth + " height " + mVideoHeight);
mSurfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
mVideoLength = mMediaPlayer.getDuration();
mTextViewFullTime.setText(TimeUtils.formatDuration(mVideoLength / 1000));
mMediaPlayer.start();
if (mPlayerType == TYPE_VOD_CONNECTED || mPlayerType == TYPE_VOD_EMULATED) {
mHandler.post(mRunnableProgressBarUpdate);
}
}
public void onPrepared(final MediaPlayer mediaPlayer) {
Log.d(LOG_TAG, "onPrepared");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoDimensionsKnown) {
startVideoPlayback();
}
}
public void onVideoSizeChanged(final MediaPlayer mediaPlayer, final int width, final int height) {
Log.d(LOG_TAG, "OnVideoSizeChanged");
if (width > 0 && height > 0) {
mVideoHeight = height;
mVideoWidth = width;
mIsVideoDimensionsKnown = true;
if (mIsVideoReadyToBePlayed && mIsVideoDimensionsKnown) {
startVideoPlayback();
}
}
}
public boolean onError(final MediaPlayer mediaPlayer, final int what, final int extra) {
doCleanUp();
showErrorMessage("An error occurred");
return false;
}
public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) {
if (fromUser) {
if (mVideoLength > 0) {
final int currentPosition = ((int) Math.floor(progress / 100f * mVideoLength)) / 1000;
mTextViewCurrentTime.setText(TimeUtils.formatDuration(currentPosition));
} else {
mTextViewCurrentTime.setText("");
}
}
}
public void onStartTrackingTouch(final SeekBar seekBar) {
if (mPlayerType == TYPE_VOD_CONNECTED || mPlayerType == TYPE_VOD_EMULATED) {
mHandler.removeCallbacks(mRunnableProgressBarUpdate);
}
pressPauseButton();
}
public void onStopTrackingTouch(final SeekBar seekBar) {
if (mPlayerType == TYPE_VOD_CONNECTED || mPlayerType == TYPE_VOD_EMULATED) {
mHandler.post(mRunnableProgressBarUpdate);
}
final int currentPosition = (int) Math.floor(mSeekBar.getProgress() / 100f * mVideoLength);
try {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(currentPosition);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
pressPlayButton();
}
public void onCompletion(final MediaPlayer mediaPlayer) {
mMediaPlayer.seekTo(0);
mSeekBar.setProgress(0);
mTextViewCurrentTime.setText(TimeUtils.formatDuration(0));
mButtonPlay.setVisibility(View.VISIBLE);
mButtonPause.setVisibility(View.GONE);
}
public void onCacheRequestFinished(ResponseBusinessObject response) {
}
public void onDataFromDatabase(int code, ArrayList<?> data) {
}
public void onRequestFinished(int requestId, boolean suceed, BusinessResponse response) {
if (Config.SHOW_LOG) {
Log.d(LOG_TAG, "onRequestFinished: " + requestId);
}
try {
if (requestId == mRequestId) {
mDataManager.removeOnDataListener(mRequestId, this);
mRequestId = -1;
final GetSessionUrl urlResponse = (GetSessionUrl) response.response;
mFilePath = urlResponse.mSessionUrl;
if (Config.SHOW_LOG) {
Log.d(LOG_TAG, "onRequestFinished, mFilePath: " + mFilePath);
}
if (mFilePath != null) {
playVideo();
} else {
showErrorMessage(mErrorGettingVideo);
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "onRequestFinished", e);
}
}
@Override
public void onBufferingUpdate(MediaPlayer mPlayer, int percent) {
// TODO Auto-generated method stub
}
}
Commented lines are the lines when i had still not used Vitamio.
Please help me to implement, modify this code to make it works !
Regards,
Julian.
I found !!!!
I stopped Vitamio library by deleting all the import of it, methods, deleted all the commentary to get back to the android libray. I commented the line : mMediaPlayer.setLooping(...); and added mMediaPlayer.start() at the end of that lines and it works !
But...yes there is a but...the appli crash at the end of the stream and during playing we cannot get back to the previous page and then the appli crash too
Is someone have ideas ?
anyone ?
The code of the method playVideo() is like that:
Code:
private void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(mFilePath);
mMediaPlayer.setDisplay(mSurfaceHolder);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.seekTo(mResumePosition);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
/*mMediaPlayer = new MediaPlayer(this);
mMediaPlayer.setDataSource(mFilePath);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.prepare();
mMediaPlayer.seekTo(mResumePosition);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
//mMediaPlayer.setAudioTrack(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);*/
} catch (Exception e) {
Log.e(LOG_TAG, "error: " + e.getMessage(), e);
showErrorMessage(mErrorPlayingVideo);
// Toast.makeText(this, "Impossible de jouer la vidéo",
// 5000).show();
}
}
The code of the activity like that now :
Code:
package fr.niji.broadpeak.activity;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
/*import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.MediaPlayer.OnBufferingUpdateListener;
import io.vov.vitamio.MediaPlayer.OnCompletionListener;
import io.vov.vitamio.MediaPlayer.OnErrorListener;
import io.vov.vitamio.MediaPlayer.OnPreparedListener;
import io.vov.vitamio.MediaPlayer.OnVideoSizeChangedListener;
import io.vov.vitamio.VitamioInstaller;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;*/
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
//import io.vov.vitamio.widget.VideoView;
import android.view.View;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import fr.niji.broadpeak.R;
import fr.niji.broadpeak.dataproxy.service.BroadpeakDataManager;
import fr.niji.broadpeak.dataproxy.webservice.getsessionurl.GetSessionUrl;
import fr.niji.broadpeak.util.Config;
import fr.niji.broadpeak.util.Resources;
import fr.niji.broadpeak.util.TimeUtils;
import fr.niji.lib.dataproxy.model.ResponseBusinessObject;
import fr.niji.lib.dataproxy.service.DataManager.OnDataListener;
import fr.niji.lib.dataproxy.service.model.BusinessResponse;
public class BroadpeakDemoPlayer extends Activity implements OnClickListener, OnPreparedListener, OnErrorListener,
OnVideoSizeChangedListener, Callback, OnSeekBarChangeListener, OnCompletionListener, OnDataListener, OnBufferingUpdateListener{
private static final String LOG_TAG = BroadpeakDemoPlayer.class.getSimpleName();
public static final String PLAYER_FILE_PATH = "playerLivePath";
public static final String PLAYER_FILE_ID = "playerFileId";
public static final String PLAYER_TYPE = "playerType";
public static final String PLAYER_RESUME_POSITION = "playerResumePosition";
public static final int TYPE_VOD_CONNECTED = 1;
public static final int TYPE_VOD_EMULATED = 2;
public static final int TYPE_LIVE_CONNECTED = 3;
public static final int TYPE_LIVE_EMULATED = 4;
private static final int DELTA_RW_FW = 5000;
private static final int DELTA_LIVE = 30000;
private static final int PROGRESS_BAR_UPDATE_DELAY = 1500;
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private MediaPlayer mMediaPlayer;
//VitamioInstaller vitamioInstaller;
private int mPlayerType;
private String mFilePath;
private String mFileId;
private int mResumePosition;
int percentBuffer;
private Toast mToast;
private WakeLock mWakeLock;
private int mTerminalType;
private String mUserId;
private int mLastPosition;
private RelativeLayout mLayoutControls;
private boolean mIsLayoutControlsVisible = true;
private SeekBar mSeekBar;
private TextView mTextViewCurrentTime;
private TextView mTextViewFullTime;
private ImageButton mButtonStartOver;
private ImageButton mButtonPlay;
private ImageButton mButtonPause;
private ImageButton mButtonRewind;
private ImageButton mButtonForward;
private ImageButton mButtonLive;
private boolean mIsButtonLiveEnabled = true;
private boolean mIsVideoReadyToBePlayed = false;
private boolean mIsVideoDimensionsKnown = false;
private int mVideoHeight = 0;
private int mVideoWidth = 0;
private int mVideoLength = -1;
private int mRequestId = -1;
private Runnable mRunnableProgressBarUpdate;
private Handler mHandler = new Handler();
private BroadpeakDataManager mDataManager;
private String mErrorGettingVideo;
private String mErrorPlayingVideo;
@Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
Intent intent = getIntent();
mDataManager = BroadpeakDataManager.getInstance(this);
mErrorGettingVideo = getString(R.string.error_getting_video_url);
mErrorPlayingVideo = getString(R.string.error_playing_video);
if (intent != null) {
mPlayerType = intent.getIntExtra(PLAYER_TYPE, 0);
mFilePath = intent.getStringExtra(PLAYER_FILE_PATH);
mFileId = intent.getStringExtra(PLAYER_FILE_ID);
if (Config.SHOW_LOG) {
Log.d(LOG_TAG, "mFilePath: " + mFilePath);
Log.d(LOG_TAG, "mFileId: " + mFileId);
}
mResumePosition = intent.getIntExtra(PLAYER_RESUME_POSITION, 0);
// must retrieve url ?
if (mFilePath == null || mFilePath.length() == 0) {
try {
mRequestId = mDataManager.getSessionUrl(this, mFileId, Resources.getInstance().mUserId);
mDataManager.addOnDataListener(mRequestId, this);
} catch (final UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
setContentView(R.layout.player);
// Decalage a 30s pour le live emulated
if (mPlayerType == TYPE_LIVE_EMULATED) {
mResumePosition = Config.LIVE_DEFAULT_OFFSET;
}
// Player management
//mSurfaceView = (SurfaceView) findViewById(R.id.surface_live);
mSurfaceView = (SurfaceView) findViewById(R.id.surface_live);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// Controls management
mLayoutControls = (RelativeLayout) findViewById(R.id.player_controls);
mLayoutControls.setClickable(true);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mSeekBar.setOnSeekBarChangeListener(this);
mTextViewCurrentTime = (TextView) findViewById(R.id.textview_current_time);
mTextViewFullTime = (TextView) findViewById(R.id.textview_full_time);
mButtonStartOver = (ImageButton) findViewById(R.id.btn_startover);
mButtonStartOver.setOnClickListener(this);
mButtonPlay = (ImageButton) findViewById(R.id.btn_play);
mButtonPlay.setOnClickListener(this);
mButtonPause = (ImageButton) findViewById(R.id.btn_pause);
mButtonPause.setOnClickListener(this);
mButtonRewind = (ImageButton) findViewById(R.id.btn_rw);
mButtonRewind.setOnClickListener(this);
mButtonForward = (ImageButton) findViewById(R.id.btn_fw);
mButtonForward.setOnClickListener(this);
mButtonLive = (ImageButton) findViewById(R.id.btn_live);
mButtonLive.setOnClickListener(this);
Resources resources = Resources.getInstance();
mTerminalType = resources.mTerminalType;
mUserId = resources.mUserId;
// Player type management
switch (mPlayerType) {
case TYPE_LIVE_CONNECTED:
mLayoutControls.setVisibility(View.GONE);
mIsLayoutControlsVisible = false;
break;
case TYPE_LIVE_EMULATED:
mSeekBar.setVisibility(View.GONE);
mTextViewCurrentTime.setVisibility(View.GONE);
mTextViewFullTime.setVisibility(View.GONE);
break;
case TYPE_VOD_CONNECTED:
mButtonStartOver.setVisibility(View.GONE);
mButtonLive.setVisibility(View.GONE);
break;
case TYPE_VOD_EMULATED:
mButtonStartOver.setVisibility(View.GONE);
mButtonLive.setVisibility(View.GONE);
break;
}
mRunnableProgressBarUpdate = new Runnable() {
public void run() {
mHandler.removeCallbacks(mRunnableProgressBarUpdate);
int progress = -1;
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
if (mVideoLength > 0) {
final int currentPosition = mMediaPlayer.getCurrentPosition();
progress = (int) Math.floor(currentPosition / (float) mVideoLength * 100);
mSeekBar.setProgress(progress);
mTextViewCurrentTime.setText(TimeUtils.formatDuration(currentPosition / 1000));
} else {
progress = 0;
mSeekBar.setProgress(progress);
mTextViewCurrentTime.setText("");
}
}
mHandler.postDelayed(mRunnableProgressBarUpdate, PROGRESS_BAR_UPDATE_DELAY);
}
};
}
@Override
protected void onResume() {
super.onResume();
acquireWakeLock();
}
@Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
releaseWakeLock();
}
@Override
protected void onStop() {
super.onStop();
if (mPlayerType == TYPE_VOD_CONNECTED) {
try {
BroadpeakDataManager.getInstance(this).retrieveSetLastPlay(BroadpeakDataManager.TYPE_NETWORK, null,
mTerminalType, mUserId, mFileId, mLastPosition, -1);
} catch (UnsupportedEncodingException e) {
Log.e(LOG_TAG, "Error while calling setLastPlay", e);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
public void surfaceChanged(final SurfaceHolder holder, final int format, final int width, final int height) {
Log.d(LOG_TAG, "surfaceChanged called");
}
public void surfaceDestroyed(final SurfaceHolder holder) {
Log.d(LOG_TAG, "surfaceDestroyed called");
}
public void surfaceCreated(final SurfaceHolder holder) {
Log.d(LOG_TAG, "surfaceCreated called");
if (mFilePath != null) {
playVideo();
}
}
public void onClick(final View view) {
if (view == mSurfaceView) {
if (mPlayerType != TYPE_LIVE_CONNECTED) {
mLayoutControls.setVisibility(mIsLayoutControlsVisible ? View.GONE : View.VISIBLE);
mIsLayoutControlsVisible = !mIsLayoutControlsVisible;
}
} else if (view == mButtonPlay) {
pressPlayButton();
} else if (view == mButtonPause) {
pressPauseButton();
} else if (view == mButtonRewind) {
if (mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED) {
mButtonLive.setEnabled(true);
mButtonForward.setEnabled(true);
mIsButtonLiveEnabled = true;
}
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition() - DELTA_RW_FW);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
} else if (view == mButtonForward) {
if (mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED) {
mButtonStartOver.setEnabled(true);
}
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition() + DELTA_RW_FW);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
} else if (view == mButtonLive) {
mButtonForward.setEnabled(false);
mButtonLive.setEnabled(false);
mIsButtonLiveEnabled = false;
mButtonStartOver.setEnabled(true);
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition() + DELTA_LIVE);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
} else if (view == mButtonStartOver) {
mButtonLive.setEnabled(true);
mButtonForward.setEnabled(true);
mIsButtonLiveEnabled = true;
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.seekTo(0);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
}
}
private void pressPauseButton() {
mButtonPlay.setVisibility(View.VISIBLE);
mButtonPause.setVisibility(View.GONE);
mButtonForward.setEnabled(false);
mButtonRewind.setEnabled(false);
if (mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED) {
mButtonLive.setEnabled(false);
mButtonStartOver.setEnabled(false);
}
try {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
}
private void pressPlayButton() {
mButtonPlay.setVisibility(View.GONE);
mButtonPause.setVisibility(View.VISIBLE);
if (mPlayerType == TYPE_LIVE_CONNECTED || mPlayerType == TYPE_LIVE_EMULATED) {
if (mIsButtonLiveEnabled) {
mButtonLive.setEnabled(true);
mButtonForward.setEnabled(true);
}
mButtonRewind.setEnabled(true);
mButtonStartOver.setEnabled(true);
} else {
mButtonRewind.setEnabled(true);
mButtonForward.setEnabled(true);
}
try {
if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
}
private void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(mFilePath);
mMediaPlayer.setDisplay(mSurfaceHolder);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.seekTo(mResumePosition);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
/*mMediaPlayer = new MediaPlayer(this);
mMediaPlayer.setDataSource(mFilePath);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.prepare();
mMediaPlayer.seekTo(mResumePosition);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
//mMediaPlayer.setAudioTrack(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);*/
} catch (Exception e) {
Log.e(LOG_TAG, "error: " + e.getMessage(), e);
showErrorMessage(mErrorPlayingVideo);
// Toast.makeText(this, "Impossible de jouer la vidéo",
// 5000).show();
}
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mLastPosition = mMediaPlayer.getCurrentPosition() / 1000;
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mVideoLength = -1;
mIsVideoReadyToBePlayed = false;
mIsVideoDimensionsKnown = false;
mHandler.removeCallbacks(mRunnableProgressBarUpdate);
}
private void acquireWakeLock() {
PowerManager.WakeLock wl = mWakeLock;
if (wl == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, LOG_TAG);
}
if (!wl.isHeld()) {
wl.acquire();
Log.d(LOG_TAG, "acquire wakelock");
}
}
private void releaseWakeLock() {
PowerManager.WakeLock wl = mWakeLock;
if (wl != null) {
if (wl.isHeld()) {
wl.release();
Log.d(LOG_TAG, "release wakelock");
}
}
}
private void showErrorMessage(final String string) {
if (mToast != null) {
mToast.cancel();
mToast.setText(string);
} else {
mToast = Toast.makeText(this, string, Toast.LENGTH_LONG);
}
mToast.show();
}
private void startVideoPlayback() {
Log.d(LOG_TAG, "startReading: width " + mVideoWidth + " height " + mVideoHeight);
mSurfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
mVideoLength = mMediaPlayer.getDuration();
mTextViewFullTime.setText(TimeUtils.formatDuration(mVideoLength / 1000));
mMediaPlayer.start();
if (mPlayerType == TYPE_VOD_CONNECTED || mPlayerType == TYPE_VOD_EMULATED) {
mHandler.post(mRunnableProgressBarUpdate);
}
}
public void onPrepared(final MediaPlayer mediaPlayer) {
Log.d(LOG_TAG, "onPrepared");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoDimensionsKnown) {
startVideoPlayback();
}
}
public void onVideoSizeChanged(final MediaPlayer mediaPlayer, final int width, final int height) {
Log.d(LOG_TAG, "OnVideoSizeChanged");
if (width > 0 && height > 0) {
mVideoHeight = height;
mVideoWidth = width;
mIsVideoDimensionsKnown = true;
if (mIsVideoReadyToBePlayed && mIsVideoDimensionsKnown) {
startVideoPlayback();
}
}
}
public boolean onError(final MediaPlayer mediaPlayer, final int what, final int extra) {
doCleanUp();
showErrorMessage("An error occurred");
return false;
}
public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) {
if (fromUser) {
if (mVideoLength > 0) {
final int currentPosition = ((int) Math.floor(progress / 100f * mVideoLength)) / 1000;
mTextViewCurrentTime.setText(TimeUtils.formatDuration(currentPosition));
} else {
mTextViewCurrentTime.setText("");
}
}
}
public void onStartTrackingTouch(final SeekBar seekBar) {
if (mPlayerType == TYPE_VOD_CONNECTED || mPlayerType == TYPE_VOD_EMULATED) {
mHandler.removeCallbacks(mRunnableProgressBarUpdate);
}
pressPauseButton();
}
public void onStopTrackingTouch(final SeekBar seekBar) {
if (mPlayerType == TYPE_VOD_CONNECTED || mPlayerType == TYPE_VOD_EMULATED) {
mHandler.post(mRunnableProgressBarUpdate);
}
final int currentPosition = (int) Math.floor(mSeekBar.getProgress() / 100f * mVideoLength);
try {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(currentPosition);
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred", e);
}
pressPlayButton();
}
public void onCompletion(final MediaPlayer mediaPlayer) {
mMediaPlayer.seekTo(0);
mSeekBar.setProgress(0);
mTextViewCurrentTime.setText(TimeUtils.formatDuration(0));
mButtonPlay.setVisibility(View.VISIBLE);
mButtonPause.setVisibility(View.GONE);
}
public void onCacheRequestFinished(ResponseBusinessObject response) {
}
public void onDataFromDatabase(int code, ArrayList<?> data) {
}
public void onRequestFinished(int requestId, boolean suceed, BusinessResponse response) {
if (Config.SHOW_LOG) {
Log.d(LOG_TAG, "onRequestFinished: " + requestId);
}
try {
if (requestId == mRequestId) {
mDataManager.removeOnDataListener(mRequestId, this);
mRequestId = -1;
final GetSessionUrl urlResponse = (GetSessionUrl) response.response;
mFilePath = urlResponse.mSessionUrl;
if (Config.SHOW_LOG) {
Log.d(LOG_TAG, "onRequestFinished, mFilePath: " + mFilePath);
}
if (mFilePath != null) {
playVideo();
} else {
showErrorMessage(mErrorGettingVideo);
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "onRequestFinished", e);
}
}
@Override
public void onBufferingUpdate(MediaPlayer mPlayer, int percent) {
// TODO Auto-generated method stub
}
}
Ok when I now there is some sound changing place the functions of the method playVideo().
But now there are two problems :
1) setLooping(true) makes en Error (-38,0) if it's activated so my lives can't loop.
2) seekTo(mResumePosition), when activated, (after deleting commentaries) disable the sound of the .m3u8 file (not for .mp4) and the player make a long time before to close and then make the appli crash
Here's the code :
Code:
private void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(mFilePath);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setOnCompletionListener(this);
//mMediaPlayer.setLooping(true);
mMediaPlayer.seekTo(mResumePosition);
} catch (Exception e) {
Log.e(LOG_TAG, "error: " + e.getMessage(), e);
showErrorMessage(mErrorPlayingVideo);
// Toast.makeText(this, "Impossible de jouer la vidéo",
// 5000).show();
}
}
A new problem is arrived.
When i click on Resume button, the video goes to the last place when I stopped the player but there is no sound...
If someone has ideas...
I have already service up and running. So that is working well. Now I am stuck with startForeground. My notifications dont seem to show so I believe startForeground isnt working as well.
I am developing for API range 10-17
I already tried several tutorials without luck
Is someone willing to help me out?
http://www28.zippyshare.com/v/73408891/file.html
Code:
package jonashendrickx.radioplayer.rgrfm;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class RadioService extends Service implements OnErrorListener {
private final IBinder mBinder = new RadioBinder();
private MediaPlayer mMediaPlayer;
private final String[] mirrors = {
"http://stream.intronic.nl/rgrfm",
"http://shoutcast01.edpnet.net:10210"
};
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
@Override
public void onCreate() {
initializeMediaPlayer();
startPlaying();
}
@Override
public void onDestroy() {
stopPlaying();
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.stop();
mp.release();
return false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_STICKY;
}
private void initializeMediaPlayer() {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(mirrors[0]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void startPlaying() {
try {
mMediaPlayer.setOnErrorListener(this);
mMediaPlayer.prepareAsync();
} catch (IllegalStateException ex) {
ex.printStackTrace();
return;
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mMediaPlayer.start();
}
});
}
private void stopPlaying() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.release();
initializeMediaPlayer();
}
}
public class RadioBinder extends Binder {
RadioService getService() {
return RadioService.this;
}
}
}
Code:
package jonashendrickx.radioplayer.rgrfm;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnClickListener {
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
mRadioService = ((RadioService.RadioBinder)service).getService();
}
@Override
public void onServiceDisconnected(ComponentName className) {
mRadioService = null;
mToggleButtonMediaPlayer.setChecked(false);
}
};
private RadioService mRadioService;
private boolean mIsBound;
private ToggleButton mToggleButtonMediaPlayer;
@Override
public void onClick(View view) {
if (view.equals(mToggleButtonMediaPlayer)) {
if (mRadioService == null) {
doBindService();
} else {
doUnbindService();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToggleButtonMediaPlayer = (ToggleButton)findViewById(R.id.toggleButtonMediaPlayer);
mToggleButtonMediaPlayer.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
void doBindService() {
bindService(new Intent(this, RadioService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
}
djjonastybe said:
I have already service up and running. So that is working well. Now I am stuck with startForeground. My notifications dont seem to show so I believe startForeground isnt working as well.
I am developing for API range 10-17
I already tried several tutorials without luck
Is someone willing to help me out?
http://www28.zippyshare.com/v/73408891/file.html
Click to expand...
Click to collapse
Where do you call startForeground? I can see just bind.
EDIT: I did not check the zip file as I never download any files if I don't know whether I can trust them. Nothing against you.
EDIT: You could try something like this: (I didn't test it)
Code:
private static final int NOTIFICATION_ID = 7392749; //value doen't matter
@Override
public void runInForeground() {
Notification n = new Notification(R.drawable.ic_launcher, "music is playing", System.currentTimeMillis());
PendingIntent i = PendingIntent.getActivity(this, 0, null, 0);
n.setLatestEventInfo(this, "Music Player", "Playing some music", i);
startForeground(NOTIFICATION_ID, n);
}
EDIT: You could also check out this project: https://github.com/commonsguy/cw-android/tree/master/Notifications/FakePlayer
Hi,
I´ve a big problem with the "getScanResults()" function. I always get "0" as result.
Here is my Code (it´s a service):
Code:
public void onCreate() {
super.onCreate();
wifiMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
intentScan = new IntentFilter();
intentScan.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
scanReceiver = new ScanReceiver();
screenOnReceiver = new ScreenOnReceiver();
registerReceiver(screenOnReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
screenOffReceiver = new ScreenOffReceiver();
registerReceiver(screenOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
[user=439709]@override[/user]
public void onDestroy () {
unregisterReceiver(screenOnReceiver);
unregisterReceiver(screenOffReceiver);
}
[user=439709]@override[/user]
public void onStart(Intent intent, int startId) {
wifiMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
registerReceiver(scanReceiver, intentScan);
showToasts = sharedPreferences.getBoolean("checkbox_notification", true);
autoSync = sharedPreferences.getBoolean("checkbox_autosync", true);
if(wifiMgr.getConnectionInfo().getNetworkId() == -1) {
if(wifiMgr.setWifiEnabled(true)) {
if(!wifiMgr.startScan()){
unregisterReceiver(scanReceiver);
}
}
}else{
if(showToasts)
Toast.makeText(this.getApplicationContext(),R.string.toast_nochange, Toast.LENGTH_SHORT).show();
}
}
public class ScanReceiver extends BroadcastReceiver {
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
Log.d("wifi", "ScanComplete - "+intent.getAction());
List<WifiConfiguration> wifiListSupplicant = wifiMgr.getConfiguredNetworks();
List<ScanResult> wifiListScan = wifiMgr.getScanResults();
Log.d("wifi", "LIST: "+wifiListScan.size());
} }
Somebody an idea?
Thanks"
I have a problem that my monkeyboard Dab receiver needs audio in. This can be switched with the avin app. But I only need the Audio switched not the video. Is it possible to make a Task with Tasker or similar to run some code or script to switch the audio.
Because also after boot the avin app is blocking the system. For example pppwidget starts only after exiting the avin app.
I also did take a look at the code of the app but I am a completely noob at java app programming and could not identify the code for switching the audio.
Can anyone understand and help me please?
Thanks
I am on malaysk kitkat rom.
here is the code i could decompile. Maybe it is useful for my Problem
MTCAVIN.apk com microntek avin AVINActivity.java
package com.microntek.avin;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.System;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
public class AVINActivity extends Activity {
private static boolean activityVisible;
private static boolean statusbarshow;
private static boolean videoEnable;
private BroadcastReceiver AVINBootReceiver;
private final int MSG_CAPTURE_OFF;
private final int MSG_CAPTURE_ON;
private final int MSG_TIME_TICK;
private final int MSG_VIDEO_CHECK;
private AudioManager am;
private Handler mHandler;
private ImageView mImageBlack;
private ImageView mImageScreen;
private boolean mInChannel;
private boolean mIsSignal;
private View mTextWarning;
private View signalshow;
private int startbackflag;
private int statusbarhidetime;
/* renamed from: com.microntek.avin.AVINActivity.1 */
class C00001 extends Handler {
C00001() {
}
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 65281:
AVINActivity.this.captureOn();
case 65282:
AVINActivity.this.captureOff();
case 65283:
AVINActivity.this.videoCheck();
case 65284:
AVINActivity.this.refresTick();
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65284, 1000);
default:
}
}
}
/* renamed from: com.microntek.avin.AVINActivity.2 */
class C00012 implements OnClickListener {
C00012() {
}
public void onClick(View v) {
if (!AVINActivity.statusbarshow) {
AVINActivity.statusbarshow = true;
AVINActivity.this.mHandler.removeMessages(65284);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65284, 1000);
AVINActivity.this.statusbarhidetime = 0;
AVINActivity.this.resumeStatusBar();
} else if (AVINActivity.this.mIsSignal && AVINActivity.videoEnable) {
AVINActivity.statusbarshow = false;
AVINActivity.this.hideStatusBar();
}
}
}
/* renamed from: com.microntek.avin.AVINActivity.3 */
class C00023 extends BroadcastReceiver {
C00023() {
}
public void onReceive(Context arg0, Intent arg1) {
String action = arg1.getAction();
if (action.equals("com.microntek.bootcheck")) {
String classname = arg1.getStringExtra("class");
if (!classname.equals("com.microntek.avin") && !classname.equals("phonecallin") && !classname.equals("phonecallout")) {
AVINActivity.this.sendFinish();
}
} else if (action.equals("com.microntek.carstatechange")) {
if (AVINActivity.activityVisible && arg1.getStringExtra("type").equals("SAFE")) {
AVINActivity.videoEnable = AVINActivity.this.GetDrivingVideoEnable();
AVINActivity.this.mHandler.removeMessages(65283);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
} else if (action.equals("com.microntek.videosignalchange") && arg1.getStringExtra("type").equals("avin")) {
AVINActivity.this.mIsSignal = arg1.getBooleanExtra("sta", true);
AVINActivity.videoEnable = AVINActivity.this.GetDrivingVideoEnable();
AVINActivity.this.mHandler.removeMessages(65283);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
}
}
public AVINActivity() {
this.MSG_CAPTURE_ON = 65281;
this.MSG_CAPTURE_OFF = 65282;
this.MSG_VIDEO_CHECK = 65283;
this.MSG_TIME_TICK = 65284;
this.mImageBlack = null;
this.mTextWarning = null;
this.signalshow = null;
this.mImageScreen = null;
this.mIsSignal = true;
this.startbackflag = 0;
this.statusbarhidetime = 0;
this.am = null;
this.mInChannel = false;
this.mHandler = new C00001();
this.AVINBootReceiver = new C00023();
}
static {
videoEnable = false;
activityVisible = false;
statusbarshow = true;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.startbackflag = getIntent().getIntExtra("start", 0);
if (this.startbackflag != 0) {
moveTaskToBack(true);
}
Intent it1 = new Intent("com.microntek.bootcheck");
it1.putExtra("class", "com.microntek.avin");
sendBroadcast(it1);
this.am = (AudioManager) getSystemService("audio");
this.statusbarhidetime = 0;
setContentView(R.layout.main);
this.signalshow = findViewById(R.id.signalshow);
this.mImageScreen = (ImageView) findViewById(R.id.screen);
this.mImageScreen.setOnClickListener(new C00012());
this.mImageBlack = (ImageView) findViewById(R.id.black);
this.mTextWarning = findViewById(R.id.safewarning);
IntentFilter itfl = new IntentFilter();
itfl.addAction("com.microntek.bootcheck");
itfl.addAction("com.microntek.carstatechange");
itfl.addAction("com.microntek.videosignalchange");
registerReceiver(this.AVINBootReceiver, itfl);
deviceOn();
sendCanBusAvinOn();
this.mHandler.sendEmptyMessageDelayed(65284, 1000);
}
private void sendFinish() {
deviceOff();
finish();
}
private void deviceOn() {
if (!this.mInChannel) {
this.am.setParameters("av_channel_enter=line");
this.mInChannel = true;
}
}
private void deviceOff() {
if (this.mInChannel) {
this.mInChannel = false;
this.am.setParameters("av_channel_exit=line");
}
}
private void sendCanBusAvinOn() {
Intent it1 = new Intent("com.microntek.canbusdisplay");
it1.putExtra("type", "avin-on");
sendBroadcast(it1);
}
private void sendCanBusAvinOff() {
Intent it1 = new Intent("com.microntek.canbusdisplay");
it1.putExtra("type", "avin-off");
sendBroadcast(it1);
}
public void onBackPressed() {
sendFinish();
}
private void refresTick() {
if (!this.mIsSignal) {
boolean en = GetDrivingVideoEnable();
if (videoEnable != en) {
videoEnable = en;
this.mHandler.removeMessages(65283);
this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
}
if (this.statusbarhidetime < 10) {
this.statusbarhidetime++;
if (this.statusbarhidetime == 10 && videoEnable && statusbarshow) {
statusbarshow = false;
hideStatusBar();
}
}
}
private boolean GetDrivingVideoEnable() {
if (System.getInt(getContentResolver(), "DrivingVideoEN", 0) != 0) {
return true;
}
if (this.am.getParameters("sta_driving=").equals("true")) {
return false;
}
return true;
}
public void hideStatusBar() {
if (this.mIsSignal) {
Window win = getWindow();
LayoutParams winParams = win.getAttributes();
winParams.flags |= 1024;
win.setAttributes(winParams);
}
}
public void resumeStatusBar() {
Window win = getWindow();
LayoutParams winParams = win.getAttributes();
winParams.flags &= -1025;
win.setAttributes(winParams);
}
protected void onResume() {
super.onResume();
statusbarshow = true;
activityVisible = true;
resumeStatusBar();
captureOn();
videoEnable = GetDrivingVideoEnable();
this.mHandler.sendEmptyMessageDelayed(65283, 100);
sendBroadcast(new Intent("com.microntek.musicclockreset"));
}
protected void onPause() {
activityVisible = false;
captureOff();
super.onPause();
}
protected void onDestroy() {
this.mHandler.removeCallbacksAndMessages(null);
unregisterReceiver(this.AVINBootReceiver);
deviceOff();
sendCanBusAvinOff();
super.onDestroy();
}
protected void videoCheck() {
if (videoEnable) {
this.mTextWarning.setVisibility(4);
} else {
this.mTextWarning.setVisibility(0);
}
if (this.mIsSignal) {
this.signalshow.setVisibility(8);
return;
}
this.signalshow.setVisibility(0);
this.statusbarhidetime = 0;
if (!statusbarshow) {
resumeStatusBar();
}
statusbarshow = true;
}
protected void captureOn() {
this.am.setParameters("ctl_capture_on=line");
this.mImageBlack.setVisibility(4);
}
protected void captureOff() {
this.mImageBlack.setVisibility(0);
this.am.setParameters("ctl_capture_off=line");
}
}
Privacy Policy
Maybe simple shell command or something? Anyone?
I did a simple Tweak in the Avin app. Now it launches without Ui. For audio in only and only for kitkat roms.
I have a typo in the attached APK...
Hey there, sorry to disturb the old thread I need avin.apk only to show video input, and not cut audio in background for Spotify. Do you think I have a chance?
I suppose It is the direct oppossite of yours.
ivellios said:
Hey there, sorry to disturb the old thread I need avin.apk only to show video input, and not cut audio in background for Spotify. Do you think I have a chance?
I suppose It is the direct oppossite of yours.
Click to expand...
Click to collapse
2nd - if you're still around - can you recompile with this ?
Might be as simple as commenting out the this.am.setParameters calls
Sorry, this is not possible for me. I did not figure it out how to disable the video.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will learn how to integrate Huawei ML kit, Account kit and Location kit in Android application KnowMyBoard. Account Kit provides seamless login functionality to the app with large user base.
ML Kit provides app to easily leverage Huawei’s long-term proven expertise in machine learning to support diverse artificial intelligence (AI) applications throughout a wide range of industries.
ML kit provides various services, in this application we will be integrating its text related service like text recognition, text detection and text translation services, which helps in achieve the gaol of the application.
Location kit SDK for Android offers location-related APIs for Android apps. These APIs mainly relate to 6 functions like fused location, activity identification, geofence, high-precision location, indoor location, and geocoding. This mode is applicable to mobile phones and Huawei tablets. We are using Location kit to get location of user.
Supported Devices
Supported Countries/Regions
Supported Countries/Regions
Development Overview
You need to install Android Studio IDE and I assume that you have prior knowledge of Android application development.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
Android phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.8 or later.
Android Studio software or Visual Studio or Code installed.
HMS Core (APK) 4.X or later
Integration steps
Step 1. Huawei developer account and complete identity verification in Huawei developer website, refer to register Huawei ID.
Step 2. Create project in AppGallery Connect
Step 3. Adding HMS Core SDK
Let’s start coding
MainActivity.java
public class MainActivity extends AppCompatActivity {
LoginViewModel loginViewModel;
private MLTextAnalyzer mTextAnalyzer;
public Uri imagePath;
Bitmap bitmap;
ArrayList<String> result = new ArrayList<>();
MLLocalLangDetector myLocalLangDetector;
MLLocalTranslator myLocalTranslator;
String textRecognized;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
MyApplication.setActivity(this);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// Process the authorization result to obtain the authorization code from AuthAccount.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8888) {
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
AuthAccount authAccount = authAccountTask.getResult();
UserData userData = new UserData();
userData.setAccessToken(authAccount.getAccessToken());
userData.setCountryCode(authAccount.getCountryCode());
userData.setDisplayName(authAccount.getDisplayName());
userData.setEmail(authAccount.getEmail());
userData.setFamilyName(authAccount.getFamilyName());
userData.setGivenName(authAccount.getGivenName());
userData.setIdToken(authAccount.getIdToken());
userData.setOpenId(authAccount.getOpenId());
userData.setUid(authAccount.getUid());
userData.setPhotoUriString(authAccount.getAvatarUri().toString());
userData.setUnionId(authAccount.getUnionId());
Gson gson = new Gson();
Log.e("TAG", "sign in success : " + gson.toJson(authAccount));
loginViewModel = new ViewModelProvider(MainActivity.this).get(LoginViewModel.class);
loginViewModel.sendData(authAccount.getDisplayName());
progressDialog.dismiss();
} else {
// The sign-in failed.
Log.e("TAG", "sign in failed:" + ((ApiException) authAccountTask.getException()).getStatusCode());
progressDialog.dismiss();
}
}
if (requestCode == 2323 && resultCode == RESULT_OK && data != null) {
progressDialog.setMessage("Initializing text detection..");
progressDialog.show();
imagePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imagePath);
} catch (IOException e) {
e.printStackTrace();
Log.e("TAG", " BITMAP ERROR");
}
Log.d("TAG", "Path " + imagePath.getPath());
try {
Bitmap selectedBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
asyncAnalyzeText(selectedBitmap);
} catch (IOException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
}
private void asyncAnalyzeText(Bitmap bitmap) {
if (mTextAnalyzer == null) {
createMLTextAnalyzer();
}
MLFrame frame = MLFrame.fromBitmap(bitmap);
Task<MLText> task = mTextAnalyzer.asyncAnalyseFrame(frame);
task.addOnSuccessListener(new OnSuccessListener<MLText>() {
@Override
public void onSuccess(MLText text) {
progressDialog.setMessage("Initializing language detection..");
Log.d("TAG", "#" + text.getStringValue());
textRecognized = text.getStringValue().trim();
if(!textRecognized.isEmpty()){
// Create a local language detector.
MLLangDetectorFactory factory = MLLangDetectorFactory.getInstance();
MLLocalLangDetectorSetting setting = new MLLocalLangDetectorSetting.Factory()
// Set the minimum confidence threshold for language detection.
.setTrustedThreshold(0.01f)
.create();
myLocalLangDetector = factory.getLocalLangDetector(setting);
Task<String> firstBestDetectTask = myLocalLangDetector.firstBestDetect(textRecognized);
firstBestDetectTask.addOnSuccessListener(new OnSuccessListener<String>() {
@Override
public void onSuccess(String languageDetected) {
progressDialog.setMessage("Initializing text translation..");
// Processing logic for detection success.
Log.d("TAG", "Lang detect :" + languageDetected);
textTranslate(languageDetected, textRecognized, bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// Processing logic for detection failure.
Log.e("TAG", "Lang detect error:" + e.getMessage());
}
});
}else{
progressDialog.dismiss();
showErrorDialog("Failed to recognize text.");
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e("TAG", "Error " + e.getMessage());
}
});
}
private void showErrorDialog(String msg) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage(msg);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void textTranslate(String languageDetected, String textRecognized, Bitmap uri) {
MLApplication.initialize(getApplication());
MLApplication.getInstance().setApiKey("fDkimdjcdjjssshwQ==");
// Create an offline translator.
MLLocalTranslateSetting setting = new MLLocalTranslateSetting.Factory()
// Set the source language code. The ISO 639-1 standard is used. This parameter is mandatory. If this parameter is not set, an error may occur.
.setSourceLangCode(languageDetected)
// Set the target language code. The ISO 639-1 standard is used. This parameter is mandatory. If this parameter is not set, an error may occur.
.setTargetLangCode("en")
.create();
myLocalTranslator = MLTranslatorFactory.getInstance().getLocalTranslator(setting);
// Set the model download policy.
MLModelDownloadStrategy downloadStrategy = new MLModelDownloadStrategy.Factory()
.needWifi()// It is recommended that you download the package in a Wi-Fi environment.
.create();
// Create a download progress listener.
MLModelDownloadListener modelDownloadListener = new MLModelDownloadListener() {
@Override
public void onProcess(long alreadyDownLength, long totalLength) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Display the download progress or perform other operations.
}
});
}
};
myLocalTranslator.preparedModel(downloadStrategy, modelDownloadListener).
addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// Called when the model package is successfully downloaded.
// input is a string of less than 5000 characters.
final Task<String> task = myLocalTranslator.asyncTranslate(textRecognized);
// Before translation, ensure that the models have been successfully downloaded.
task.addOnSuccessListener(new OnSuccessListener<String>() {
@Override
public void onSuccess(String translated) {
// Processing logic for detection success.
result.clear();
result.add(languageDetected.trim());
result.add(textRecognized.trim());
result.add(translated.trim());
loginViewModel.setImage(uri);
loginViewModel.setTextRecongnized(result);
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// Processing logic for detection failure.
progressDialog.dismiss();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// Called when the model package fails to be downloaded.
progressDialog.dismiss();
}
});
}
private void createMLTextAnalyzer() {
MLLocalTextSetting setting = new MLLocalTextSetting.Factory()
.setOCRMode(MLLocalTextSetting.OCR_DETECT_MODE)
.create();
mTextAnalyzer = MLAnalyzerFactory.getInstance().getLocalTextAnalyzer(setting);
}
@Override
protected void onStop() {
if (myLocalLangDetector != null) {
myLocalLangDetector.stop();
}
if (myLocalTranslator!= null) {
myLocalTranslator.stop();
}
if(progressDialog!= null){
progressDialog.dismiss();
}
super.onStop();
}
}
LoginViewModel.java
public class LoginViewModel extends AndroidViewModel {
AccountAuthService service;
private MutableLiveData<String> message = new MutableLiveData<>();
private MutableLiveData<ArrayList<String>> textRecongnized = new MutableLiveData<>();
private MutableLiveData<Bitmap> image = new MutableLiveData<>();
private MutableLiveData<LocationResult> locationResult = new MutableLiveData<>();
public void sendData(String msg) {
message.setValue(msg);
}
public LiveData<String> getMessage() {
return message;
}
public MutableLiveData<ArrayList<String>> getTextRecongnized() {
return textRecongnized;
}
public void setImage(Bitmap imagePath) {
this.image.setValue(imagePath);
}
public MutableLiveData<LocationResult> getLocationResult() {
return locationResult;
}
public void setLocationResult(LocationResult locationResult) {
this.locationResult.setValue(locationResult);
}
public void setTextRecongnized(ArrayList<String> textRecongnized) {
this.textRecongnized.setValue(textRecongnized);
}
public MutableLiveData<Bitmap> getImagePath() {
return image;
}
public LoginViewModel(@NonNull Application application) {
super(application);
}
public void logoutHuaweiID() {
if (service != null) {
service.signOut();
sendData("KnowMyBoard");
Toast.makeText(getApplication(), "You are logged out from Huawei ID", Toast.LENGTH_LONG).show();
}
}
public void loginClicked(View view) {
AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
service = AccountAuthManager.getService(MyApplication.getActivity(), authParams);
MyApplication.getActivity().startActivityForResult(service.getSignInIntent(), 8888);
}
public void cancelAuthorization() {
if (service != null) {
// service indicates the AccountAuthService instance generated using the getService method during the sign-in authorization.
service.cancelAuthorization().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// Processing after a successful authorization cancellation.
Log.i("TAG", "onSuccess: ");
sendData("KnowMyBoard");
Toast.makeText(getApplication(), "Cancelled authorization", Toast.LENGTH_LONG).show();
} else {
// Handle the exception.
Exception exception = task.getException();
if (exception instanceof ApiException) {
int statusCode = ((ApiException) exception).getStatusCode();
Log.i("TAG", "onFailure: " + statusCode);
Toast.makeText(getApplication(), "Failed to cancel authorization", Toast.LENGTH_LONG).show();
}
}
}
});
} else {
Toast.makeText(getApplication(), "Login required", Toast.LENGTH_LONG).show();
}
}
}
[B][B]
RequestLocationData.java
apublic class RequestLocationData {
static String TAG = "TAG";
SettingsClient settingsClient;
private int isLocationSettingSuccess = 0;
private LocationRequest myLocationRequest;
// Define a fusedLocationProviderClient object.
private FusedLocationProviderClient fusedLocationProviderClient;
LocationCallback myLocationCallback;
Context context;
Activity activity;
LocationResult locationResult;
LoginViewModel loginViewModel;
public RequestLocationData(Context context, FragmentActivity activity, LoginViewModel loginViewModel) {
setContext(context);
setActivity(activity);
setLoginViewModel(loginViewModel);
}
public LoginViewModel getLoginViewModel() {
return loginViewModel;
}
public void setLoginViewModel(LoginViewModel loginViewModel) {
this.loginViewModel = loginViewModel;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public Activity getActivity() {
return activity;
}
public void setActivity(Activity activity) {
this.activity = activity;
}
public void initFusionLocationProviderClint(){
// Instantiate the fusedLocationProviderClient object.
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
settingsClient = LocationServices.getSettingsClient(getActivity());
}
public void checkDeviceLocationSettings() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
myLocationRequest = new LocationRequest();
builder.addLocationRequest(myLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check the device location settings.
settingsClient.checkLocationSettings(locationSettingsRequest)
// Define the listener for success in calling the API for checking device location settings.
.addOnSuccessListener(locationSettingsResponse -> {
LocationSettingsStates locationSettingsStates =
locationSettingsResponse.getLocationSettingsStates();
StringBuilder stringBuilder = new StringBuilder();
// Check whether the location function is enabled.
stringBuilder.append(",\nisLocationUsable=")
.append(locationSettingsStates.isLocationUsable());
// Check whether HMS Core (APK) is available.
stringBuilder.append(",\nisHMSLocationUsable=")
.append(locationSettingsStates.isHMSLocationUsable());
Log.i(TAG, "checkLocationSetting onComplete:" + stringBuilder.toString());
// Set the location type.
myLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the number of location updates to 1.
myLocationRequest.setNumUpdates(1);
isLocationSettingSuccess = 1;
})
// Define callback for failure in checking the device location settings.
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "checkLocationSetting onFailure:" + e.getMessage());
}
});
}
public void checkPermission() {
// Dynamically apply for required permissions if the API level is 28 or lower.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
Log.i(TAG, "android sdk <= 28 Q");
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] strings =
{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.MANAGE_MEDIA,Manifest.permission.MEDIA_CONTENT_CONTROL,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(getActivity(), strings, 1);
}
} else {
// Dynamically apply for the android.permission.ACCESS_BACKGROUND_LOCATION permission in addition to the preceding permissions if the API level is higher than 28.
if (ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getContext(),
"android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.MEDIA_CONTENT_CONTROL,Manifest.permission.MANAGE_MEDIA,
"android.permission.ACCESS_BACKGROUND_LOCATION"};
ActivityCompat.requestPermissions(getActivity(), strings, 2);
}
}
}
public LocationResult refreshLocation() {
if (isLocationSettingSuccess == 1) {
myLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
getLoginViewModel().setLocationResult(locationResult);
}
}
};
fusedLocationProviderClient.requestLocationUpdates(myLocationRequest, myLocationCallback, Looper.getMainLooper());
} else {
Log.d(TAG, "Failed to get location settings");
}
return locationResult;
}
public void disableLocationData(){
fusedLocationProviderClient.disableBackgroundLocation();
fusedLocationProviderClient.removeLocationUpdates(myLocationCallback);
}
}
navigation_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/navigation_graph"
app:startDestination="@id/loginFragment">
<fragment
android:id="@+id/loginFragment"
android:name="com.huawei.hms.knowmyboard.dtse.activity.fragments.LoginFragment"
android:label="LoginFragment">
<action
android:id="@+id/action_loginFragment_to_mainFragment"
app:destination="@id/mainFragment" />
</fragment>
<fragment
android:id="@+id/mainFragment"
android:name="com.huawei.hms.knowmyboard.dtse.activity.fragments.MainFragment"
android:label="MainFragment">
<action
android:id="@+id/action_mainFragment_to_loginFragment"
app:destination="@id/loginFragment" />
</fragment>
</navigation>
LoginFragment.java
public class LoginFragment extends Fragment {
FragmentLoginBinding loginBinding;
LoginViewModel loginViewModel;
Menu menu;
SharedPreferences prefs;
SharedPreferences.Editor editor;
NavController navController;
private String MY_PREF_NAME = "my_pref_name";
private String TAG = "TAG";
public LoginFragment() {
// Required empty public constructor
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
loginBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false);
loginViewModel = new ViewModelProvider(getActivity()).get(LoginViewModel.class);
loginBinding.setLoginViewModel(loginViewModel);
Log.d(TAG, " Pref " + getPreferenceValue());
if (getPreferenceValue().equals("user_name")) {
loginBinding.btnHuaweiIdAuth.setVisibility(View.VISIBLE);
} else {
enableMenu(menu);
getActivity().setTitle(getPreferenceValue());
loginBinding.btnHuaweiIdAuth.setVisibility(View.GONE);
}
loginBinding.imageLogo.setOnClickListener(v -> {
navController.navigate(R.id.action_loginFragment_to_mainFragment);
});
loginViewModel.getMessage().observeForever(new Observer<String>() {
@Override
public void onChanged(String message) {
updateMessage(message);
if (!message.equals(getResources().getString(R.string.app_name))) {
setPreferenceValue(message);
enableMenu(menu);
loginBinding.btnHuaweiIdAuth.setVisibility(View.GONE);
} else {
disableMenu(menu);
loginBinding.btnHuaweiIdAuth.setVisibility(View.VISIBLE);
setPreferenceValue("user_name");
}
}
});
return loginBinding.getRoot();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main, menu);
this.menu = menu;
disableMenu(menu);
}
private void disableMenu(Menu menu) {
try {
if (menu != null) {
if (getPreferenceValue().equals("user_name")) {
menu.findItem(R.id.menu_login_logout).setVisible(false);
menu.findItem(R.id.menu_cancel_auth).setVisible(false);
getActivity().setTitle(getResources().getString(R.string.app_name));
} else {
menu.findItem(R.id.menu_login_logout).setVisible(true);
menu.findItem(R.id.menu_cancel_auth).setVisible(true);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void enableMenu(Menu menu) {
try {
menu.findItem(R.id.menu_login_logout).setVisible(true);
menu.findItem(R.id.menu_cancel_auth).setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_cancel_auth:
setPreferenceValue("user_name");
loginViewModel.cancelAuthorization();
loginBinding.btnHuaweiIdAuth.setVisibility(View.VISIBLE);
disableMenu(menu);
return true;
case R.id.menu_login_logout:
setPreferenceValue("user_name");
loginViewModel.logoutHuaweiID();
loginBinding.btnHuaweiIdAuth.setVisibility(View.VISIBLE);
disableMenu(menu);
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void updateMessage(String msg) {
getActivity().setTitle(msg);
}
void setPreferenceValue(String userName) {
editor = getActivity().getSharedPreferences(MY_PREF_NAME, MODE_PRIVATE).edit();
editor.putString("user_name", userName);
editor.apply();
}
String getPreferenceValue() {
prefs = getActivity().getSharedPreferences(MY_PREF_NAME, MODE_PRIVATE);
return prefs.getString("user_name", "user_name");
}
}
MainFragment.java
public class MainFragment extends Fragment {
static String TAG = "TAG";
FragmentMainFragmentBinding binding;
LoginViewModel loginViewModel;
RequestLocationData locationData;
public MainFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main_fragment, container, false);
loginViewModel = new ViewModelProvider(getActivity()).get(LoginViewModel.class);
binding.setLoginViewModel(loginViewModel);
locationData = new RequestLocationData(getContext(),getActivity(),loginViewModel);
locationData.initFusionLocationProviderClint();
locationData.checkPermission();
locationData.checkDeviceLocationSettings();
binding.buttonScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseImage();
}
});
loginViewModel.getImagePath().observeForever(new Observer<Bitmap>() {
@Override
public void onChanged(Bitmap bitmap) {
try{
binding.imageView.setImageBitmap(bitmap);
}catch (Exception e){
e.printStackTrace();
Log.e("TAG","Error : "+e.getMessage());
}
}
});
loginViewModel.getTextRecongnized().observeForever(new Observer<ArrayList<String>>() {
@Override
public void onChanged(ArrayList<String> res) {
Log.i("TAG","OBSERVER : "+"Language : "+getStringResourceByName(res.get(0).trim())+
" Detected text : "+res.get(1).trim()+
" Translated text : "+res.get(2).trim());
binding.textLanguage.setText("Language : "+getStringResourceByName(res.get(0)));
binding.textDetected.setText("Detected text : "+res.get(1));
binding.textTranslated.setText("Translated text : "+res.get(2));
}
});
loginViewModel.getLocationResult().observeForever(new Observer<LocationResult>() {
@Override
public void onChanged(LocationResult locationResult) {
binding.textDetected.setText("Latitude " + locationResult.getLastHWLocation().getLatitude() + " Longitude " + locationResult.getLastHWLocation().getLongitude());
}
});
return binding.getRoot();
}
private String getStringResourceByName(String aString) {
String packageName = getActivity().getPackageName();
int resId = getResources()
.getIdentifier(aString, "string", packageName);
if (resId == 0) {
return aString;
} else {
return getString(resId);
}
}
private void chooseImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
getActivity().startActivityForResult(intent, 2323);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.main_fragment_menu, menu);
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.option_refresh_location:
//refreshLocation();
locationData.refreshLocation();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onStop() {
super.onStop();
locationData.disableLocationData();
}
}
Result
Tricks and Tips
Makes sure that agconnect-services.json file added.
Make sure required dependencies are added
Make sure that service is enabled in AGC
Images has clear visibility of text
Enable data binding in gradle.build file
Conclusion
In this article, we have learnt how to integrate Huawei Account kit, Location kit and ML kit in Android application KnowMyBoard. You can also go through previous article part-1 here. Hoping that the ML kit capabilities are helpful to you as well, like this sample, you can make use of ML kit to recognition of text and detection of language and translation of text, likewise you can make use of ML kit in tourism app which helps app users to understand different sign boards and get rid of the language barrier.
Thank you so much for reading. I hope this article helps you to understand the integration of Huawei ML kit, Account kit and Location kit in Android application KnowMyBoard.
Reference
ML Kit – Training video
Location Kit – Training video
Checkout in forum