Android Memory Game - Android Q&A, Help & Troubleshooting

I'm doing a Memory Game for android using eclipse.
In my java file, i implement the OnClickListener. Now, the problem is what should I code in the public void onClick(View v){} to match the tile.
Here are my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MemoryGame extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
//Implement the OnClickListener call back
public void onClick(View v)
{
if(v.getId() == R.id.one) {
Button btn1 = (Button) findViewById(R.id.one);
btn1.setOnClickListener(this);
}
else if (v.getId() == R.id.two)
{
Button btn2 = (Button) findViewById(R.id.two);
btn2.setOnClickListener(this);
}
else if (v.getId() == R.id.three)
{
Button btn3 = (Button) findViewById(R.id.three);
btn3.setOnClickListener(this);
}
else if (v.getId() == R.id.four)
{
Button btn4 = (Button) findViewById(R.id.four);
btn4.setOnClickListener(this);
}
else if (v.getId() == R.id.five)
{
Button btn5 = (Button) findViewById(R.id.five);
btn5.setOnClickListener(this);
}
else if (v.getId() == R.id.six)
{
Button btn6 = (Button) findViewById(R.id.six);
btn6.setOnClickListener(this);
}
else if (v.getId() == R.id.seven)
{
Button btn7 = (Button) findViewById(R.id.seven);
btn7.setOnClickListener(this);
}
else if (v.getId() == R.id.eight)
{
Button btn8 = (Button) findViewById(R.id.eight);
btn8.setOnClickListener(this);
}
else if (v.getId() == R.id.nine)
{
Button btn9 = (Button) findViewById(R.id.nine);
btn9.setOnClickListener(this);
}
else if (v.getId() == R.id.ten)
{
Button btn10 = (Button) findViewById(R.id.ten);
btn10.setOnClickListener(this);
}
else if (v.getId() == R.id.eleven)
{
Button btn11 = (Button) findViewById(R.id.eleven);
btn11.setOnClickListener(this);
}
else if (v.getId() == R.id.twelve)
{
Button btn12 = (Button) findViewById(R.id.twelve);
btn12.setOnClickListener(this);
}
}
}
Thanks.

Related

[Q] Player HLS (Http Live Streaming)code modification

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...

(REQ) How to Add Kill Long Press Kill Apps+ Long press volume keys to skip tracks

Does anyone know which jar files and smali files/codes( lines) for adding music control and long press back button to kill apps ?
I need name of files and smali codes.
I need it, too
i think its android-policy.jar or services.jar maybe.
i need it too
AW: (REQ) How to Add Kill Long Press Kill Apps+ Long press volume keys to skip tracks
me too
This is what would be added for Settings:
packages/apps/Settings/src/com/android/settings/DevelopmentSettings.java
Code:
packages/apps/Settings/src/com/android/settings/DevelopmentSettings.java
public class DevelopmentSettings extends PreferenceActivity
implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener {
private static final String KILL_APP_LONGPRESS_BACK = "kill_app_longpress_back";
private CheckBoxPreference mKillAppLongpressBack;
addPreferencesFromResource(R.xml.development_prefs);
mKillAppLongpressBack = (CheckBoxPreference) findPreference(KILL_APP_LONGPRESS_BACK);
}
@Override
protected void onResume() {
super.onResume();
mKillAppLongpressBack.setChecked(Settings.Secure.getInt(getContentResolver(),
Settings.Secure.KILL_APP_LONGPRESS_BACK, 0) != 0);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
} else if (preference == mKillAppLongpressBack) {
Settings.Secure.putInt(getContentResolver(), Settings.Secure.KILL_APP_LONGPRESS_BACK,
mKillAppLongpressBack.isChecked() ? 1 : 0);
}
And for frameworks:
policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
Code:
Runnable mBackLongPress = new Runnable() {
public void run() {
if (Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.KILL_APP_LONGPRESS_BACK, 0) == 0) {
return;
}
try {
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
IActivityManager mgr = ActivityManagerNative.getDefault();
List<RunningAppProcessInfo> apps = mgr.getRunningAppProcesses();
for (RunningAppProcessInfo appInfo : apps) {
int uid = appInfo.uid;
// Make sure it's a foreground USER application
if (uid >= Process.FIRST_APPLICATION_UID && uid <= Process.LAST_APPLICATION_UID
&& appInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
// Kill the entire pid
Toast.makeText(mContext, com.android.internal.R.string.app_killed_message, Toast.LENGTH_SHORT).show();
Process.killProcess(appInfo.pid);
break;
}
}
I SAW IT FROM SAMSUNG PHONE, NOT SURE ABOUT OUR SONY
TELL ME IF IT WORKS
TeamIndia said:
This is what would be added for Settings:
packages/apps/Settings/src/com/android/settings/DevelopmentSettings.java
Code:
packages/apps/Settings/src/com/android/settings/DevelopmentSettings.java
public class DevelopmentSettings extends PreferenceActivity
implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener {
private static final String KILL_APP_LONGPRESS_BACK = "kill_app_longpress_back";
private CheckBoxPreference mKillAppLongpressBack;
addPreferencesFromResource(R.xml.development_prefs);
mKillAppLongpressBack = (CheckBoxPreference) findPreference(KILL_APP_LONGPRESS_BACK);
}
@Override
protected void onResume() {
super.onResume();
mKillAppLongpressBack.setChecked(Settings.Secure.getInt(getContentResolver(),
Settings.Secure.KILL_APP_LONGPRESS_BACK, 0) != 0);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
} else if (preference == mKillAppLongpressBack) {
Settings.Secure.putInt(getContentResolver(), Settings.Secure.KILL_APP_LONGPRESS_BACK,
mKillAppLongpressBack.isChecked() ? 1 : 0);
}
And for frameworks:
policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
Code:
Runnable mBackLongPress = new Runnable() {
public void run() {
if (Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.KILL_APP_LONGPRESS_BACK, 0) == 0) {
return;
}
try {
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
IActivityManager mgr = ActivityManagerNative.getDefault();
List<RunningAppProcessInfo> apps = mgr.getRunningAppProcesses();
for (RunningAppProcessInfo appInfo : apps) {
int uid = appInfo.uid;
// Make sure it's a foreground USER application
if (uid >= Process.FIRST_APPLICATION_UID && uid <= Process.LAST_APPLICATION_UID
&& appInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
// Kill the entire pid
Toast.makeText(mContext, com.android.internal.R.string.app_killed_message, Toast.LENGTH_SHORT).show();
Process.killProcess(appInfo.pid);
break;
}
}
I SAW IT FROM SAMSUNG PHONE, NOT SURE ABOUT OUR SONY
TELL ME IF IT WORKS
Click to expand...
Click to collapse
no its completely different...bcz we dont u use kill concept smali...
so we have to mod android.policy.jar
settings.apk
and fw-res.apk..
iam almost making a tut for it...will add it in my tut thread soon..

problem using facebook SDK

Hi i have problem capturing the information using the facebook SDK.
The console dont show any error but capture nothing.
In this code below i want to capture the name provided by the facebook SDK
Code:
package com.eduardoh89saluguia;
import java.util.List;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
@SuppressWarnings("unused")
public class Registro extends Activity {
String get_id, get_name, get_gender, get_email, get_birthday, get_locale, get_location;
private Session.StatusCallback fbStatusCallback = new Session.StatusCallback() {
public void call(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user, Response response) {
if (response != null) {
String LOG_TAG = null;
// do something with <response> now
try{
// get_id = user.getId();
get_name = user.getName();
//get_gender = (String) user.getProperty("gender");
//get_email = (String) user.getProperty("email");
//get_birthday = user.getBirthday();
//get_locale = (String) user.getProperty("locale");
//get_location = user.getLocation().toString();
Log.d(LOG_TAG, user.getId() + "; " +
user.getName() + "; " //+
//(String) user.getProperty("gender") + "; " +
//(String) user.getProperty("email") + "; " +
//user.getBirthday()+ "; " +
//String) user.getProperty("locale") + "; " +
//user.getLocation()
);
TextView temp;
temp =(TextView)findViewById(R.id.edit1);
temp.setText("your name is "+get_name);
} catch(Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Exception e");
}
}
}
}).executeAsync();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(), Ejecucion.class);
startActivity(i);
}
});
}
private Session openActiveSession(Activity activity, boolean allowLoginUI,
StatusCallback callback, List<String> permissions, Bundle savedInstanceState) {
OpenRequest openRequest = new OpenRequest(activity).
setPermissions(permissions).setLoginBehavior(SessionLoginBehavior.
SSO_WITH_FALLBACK).setCallback(callback).
setDefaultAudience(SessionDefaultAudience.FRIENDS);
String LOG_TAG = null;
Session session = Session.getActiveSession();
Log.d(LOG_TAG, "" + session);
if (session == null) {
Log.d(LOG_TAG, "" + savedInstanceState);
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) {
session.openForRead(openRequest);
return session;
}
}
return null;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.registro, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Any Errors on this Source Code? Please help?

Hello,
I'm trying to use Janus vulnerability to get root, and I pasted the file I modified below,
Really, most of the code doesn't matter but I pasted them anyway.
Is that code starting from "public static void copyDirectory" going to work, with copying /data/local/tmp/su to /system/bin/su ?
Any help is appreciated!
Code:
package com.android.calculator2;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import android.animation.AnimatorSet.Builder;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Editable.Factory;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.ViewAnimationUtils;
import android.view.ViewGroupOverlay;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Calculator
extends Activity
implements View.OnLongClickListener, CalculatorEditText.OnTextSizeChangeListener, CalculatorExpressionEvaluator.EvaluateCallback
{
private static final String a = Calculator.class.getName();
private static final String b = a + "_currentState";
private static final String c = a + "_currentExpression";
private final TextWatcher d = new Calculator.1(this);
private final View.OnKeyListener e = new Calculator.2(this);
private final Editable.Factory f = new Calculator.3(this);
private Calculator.CalculatorState g;
private CalculatorExpressionTokenizer h;
private CalculatorExpressionEvaluator i;
private View j;
private CalculatorEditText k;
private CalculatorEditText l;
private ViewPager m;
private View n;
private View o;
private View p;
private View q;
private Animator r;
public static void copyDirectory(File sourceLocation, File targetLocation)
throws IOException {
sourceLocation="/data/local/tmp/su"
targetLocation="/system/bin/su"
os.writeBytes("mount -o remount rw /system/\n");
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdirs();
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(
targetLocation, children[i]));
}
} else {
copyFile(sourceLocation, targetLocation);
}
}
private void a()
{
if (this.g == Calculator.CalculatorState.a)
{
a(Calculator.CalculatorState.b);
this.i.a(this.k.getText(), this);
}
}
private void a(View paramView, int paramInt, Animator.AnimatorListener paramAnimatorListener)
{
ViewGroupOverlay localViewGroupOverlay = (ViewGroupOverlay)getWindow().getDecorView().getOverlay();
Object localObject = new Rect();
this.j.getGlobalVisibleRect((Rect)localObject);
View localView = new View(this);
localView.setBottom(((Rect)localObject).bottom);
localView.setLeft(((Rect)localObject).left);
localView.setRight(((Rect)localObject).right);
localView.setBackgroundColor(getResources().getColor(paramInt));
localViewGroupOverlay.add(localView);
localObject = new int[2];
paramView.getLocationInWindow((int[])localObject);
localObject[0] += paramView.getWidth() / 2;
localObject[1] += paramView.getHeight() / 2;
paramInt = localObject[0] - localView.getLeft();
int i1 = localObject[1] - localView.getTop();
double d2 = Math.pow(localView.getLeft() - paramInt, 2.0D);
double d1 = Math.pow(localView.getRight() - paramInt, 2.0D);
double d3 = Math.pow(localView.getTop() - i1, 2.0D);
paramView = ViewAnimationUtils.createCircularReveal(localView, paramInt, i1, 0.0F, (float)Math.max(Math.sqrt(d2 + d3), Math.sqrt(d1 + d3)));
paramView.setDuration(getResources().getInteger(17694722));
paramView.addListener(paramAnimatorListener);
localObject = ObjectAnimator.ofFloat(localView, View.ALPHA, new float[] { 0.0F });
((Animator)localObject).setDuration(getResources().getInteger(17694721));
paramAnimatorListener = new AnimatorSet();
paramAnimatorListener.play(paramView).before((Animator)localObject);
paramAnimatorListener.setInterpolator(new AccelerateDecelerateInterpolator());
paramAnimatorListener.addListener(new Calculator.4(this, localViewGroupOverlay, localView));
this.r = paramAnimatorListener;
paramAnimatorListener.start();
}
private void a(Calculator.CalculatorState paramCalculatorState)
{
if (this.g != paramCalculatorState)
{
this.g = paramCalculatorState;
if ((paramCalculatorState != Calculator.CalculatorState.c) && (paramCalculatorState != Calculator.CalculatorState.d)) {
break label87;
}
this.n.setVisibility(8);
this.p.setVisibility(0);
if (paramCalculatorState != Calculator.CalculatorState.d) {
break label107;
}
int i1 = getResources().getColor(2131296275);
this.k.setTextColor(i1);
this.l.setTextColor(i1);
getWindow().setStatusBarColor(i1);
}
for (;;)
{
return;
label87:
this.n.setVisibility(0);
this.p.setVisibility(8);
break;
label107:
this.k.setTextColor(getResources().getColor(2131296281));
this.l.setTextColor(getResources().getColor(2131296282));
getWindow().setStatusBarColor(getResources().getColor(2131296274));
}
}
private void b()
{
if (TextUtils.isEmpty(this.k.getText())) {}
for (;;)
{
return;
a(this.q, 2131296274, new Calculator.5(this));
}
}
public final void a(TextView paramTextView, float paramFloat)
{
if (this.g != Calculator.CalculatorState.a) {}
for (;;)
{
return;
paramFloat /= paramTextView.getTextSize();
float f4 = paramTextView.getWidth() / 2.0F;
float f3 = paramTextView.getPaddingEnd();
float f1 = paramTextView.getHeight() / 2.0F;
float f2 = paramTextView.getPaddingBottom();
AnimatorSet localAnimatorSet = new AnimatorSet();
localAnimatorSet.playTogether(new Animator[] { ObjectAnimator.ofFloat(paramTextView, View.SCALE_X, new float[] { paramFloat, 1.0F }), ObjectAnimator.ofFloat(paramTextView, View.SCALE_Y, new float[] { paramFloat, 1.0F }), ObjectAnimator.ofFloat(paramTextView, View.TRANSLATION_X, new float[] { (1.0F - paramFloat) * (f4 - f3), 0.0F }), ObjectAnimator.ofFloat(paramTextView, View.TRANSLATION_Y, new float[] { (1.0F - paramFloat) * (f1 - f2), 0.0F }) });
localAnimatorSet.setDuration(getResources().getInteger(17694721));
localAnimatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
localAnimatorSet.start();
}
}
public final void a(String paramString, int paramInt)
{
if (this.g == Calculator.CalculatorState.a) {
this.l.setText(paramString);
}
for (;;)
{
this.k.requestFocus();
return;
if (paramInt != -1)
{
this.k.announceForAccessibility(getString(paramInt));
if (this.g != Calculator.CalculatorState.b) {
this.l.setText(paramInt);
} else {
a(this.q, 2131296275, new Calculator.6(this, paramInt));
}
}
else if (!TextUtils.isEmpty(paramString))
{
this.k.announceForAccessibility(paramString);
float f3 = this.k.a(paramString) / this.l.getTextSize();
float f5 = this.l.getWidth() / 2.0F;
float f7 = this.l.getPaddingEnd();
float f2 = this.l.getHeight() / 2.0F;
float f8 = this.l.getPaddingBottom();
float f1 = this.k.getBottom() - this.l.getBottom();
float f6 = this.l.getPaddingBottom() - this.k.getPaddingBottom();
float f4 = -this.k.getBottom();
int i1 = this.l.getCurrentTextColor();
paramInt = this.k.getCurrentTextColor();
ValueAnimator localValueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), new Object[] { Integer.valueOf(i1), Integer.valueOf(paramInt) });
localValueAnimator.addUpdateListener(new Calculator.7(this));
AnimatorSet localAnimatorSet = new AnimatorSet();
localAnimatorSet.playTogether(new Animator[] { localValueAnimator, ObjectAnimator.ofFloat(this.l, View.SCALE_X, new float[] { f3 }), ObjectAnimator.ofFloat(this.l, View.SCALE_Y, new float[] { f3 }), ObjectAnimator.ofFloat(this.l, View.TRANSLATION_X, new float[] { (1.0F - f3) * (f5 - f7) }), ObjectAnimator.ofFloat(this.l, View.TRANSLATION_Y, new float[] { (1.0F - f3) * (f2 - f8) + f1 + f6 }), ObjectAnimator.ofFloat(this.k, View.TRANSLATION_Y, new float[] { f4 }) });
localAnimatorSet.setDuration(getResources().getInteger(17694722));
localAnimatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
localAnimatorSet.addListener(new Calculator.8(this, paramString, i1));
this.r = localAnimatorSet;
localAnimatorSet.start();
}
else if (this.g == Calculator.CalculatorState.b)
{
a(Calculator.CalculatorState.a);
}
}
}
public void onBackPressed()
{
if ((this.m == null) || (this.m.getCurrentItem() == 0)) {
super.onBackPressed();
}
for (;;)
{
return;
this.m.setCurrentItem(this.m.getCurrentItem() - 1);
}
}
public void onButtonClick(View paramView)
{
this.q = paramView;
switch (paramView.getId())
{
default:
this.k.append(((Button)paramView).getText());
}
for (;;)
{
return;
a();
continue;
paramView = this.k.getEditableText();
int i1 = paramView.length();
if (i1 > 0)
{
paramView.delete(i1 - 1, i1);
continue;
b();
continue;
this.k.append(((Button)paramView).getText() + "(");
}
}
}
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(2130968856);
this.j = findViewById(2131427511);
this.k = ((CalculatorEditText)findViewById(2131427512));
this.l = ((CalculatorEditText)findViewById(2131427513));
this.m = ((ViewPager)findViewById(2131427510));
this.n = findViewById(2131427557);
this.p = findViewById(2131427558);
this.o = findViewById(2131427543).findViewById(2131427555);
if ((this.o == null) || (this.o.getVisibility() != 0)) {
this.o = findViewById(2131427556).findViewById(2131427555);
}
this.h = new CalculatorExpressionTokenizer(this);
this.i = new CalculatorExpressionEvaluator(this.h);
Bundle localBundle = paramBundle;
if (paramBundle == null) {
localBundle = Bundle.EMPTY;
}
a(Calculator.CalculatorState.values()[localBundle.getInt(b, Calculator.CalculatorState.a.ordinal())]);
this.k.setText(this.h.b(localBundle.getString(c, "")));
this.i.a(this.k.getText(), this);
this.k.setEditableFactory(this.f);
this.k.addTextChangedListener(this.d);
this.k.setOnKeyListener(this.e);
this.k.setOnTextSizeChangeListener(this);
this.n.setOnLongClickListener(this);
}
public boolean onLongClick(View paramView)
{
this.q = paramView;
if (paramView.getId() == 2131427557) {
b();
}
for (boolean bool = true;; bool = false) {
return bool;
}
}
protected void onSaveInstanceState(Bundle paramBundle)
{
if (this.r != null) {
this.r.cancel();
}
super.onSaveInstanceState(paramBundle);
paramBundle.putInt(b, this.g.ordinal());
paramBundle.putString(c, this.h.a(this.k.getText().toString()));
}
public void onUserInteraction()
{
super.onUserInteraction();
if (this.r != null) {
this.r.cancel();
}
}
}
Oops, guys? This topic was buried? :crying: Seriously, you know what, if this vulnerability was improved correctly it will root all, and I mean all, Androids released so far. And I only need help for this Java part. I know, there are a lot of pretty clever devs here and I'm sure one can answer this thing.
Thanks!
#Bump
Wumpus Bumpus
Please help
Why, no one? Please? Someone help.:crying:
Bump
Bump
Bump!!!!

How to set right the file path for reading, after selecting the file with file picker in android?

In the below attached code , I am able to select file from internal storage using file picker, but unable to open the file for reading the file. code for reading the file is written, looks like its not picking the right path for opening the file, so throwing exception. Can anyone help me diagnose the issue.
package android.ble.internal_storage;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.iutputStreamWriter;
public class MainActivity extends Activity {
private static final int PERMISSION_WRITE_STORAGE = 11;
private static final int PERMISSION_READ_EXTERNAL_STORAGE = 12;
private static final int CHOOSE_TXT_FROM_DEVICE = 1;
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg = (EditText) findViewById(R.id.editText1);
}
public void WriteBtn(View v) {
try {
FileOutputStream fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE); //mytextfile.txt
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
Context context = getApplicationContext();
String folder = context.getFilesDir().getAbsolutePath();
outputWriter.write(folder + " ");
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_TXT_FROM_DEVICE && resultCode == Activity.RESULT_OK) {
if (data != null) {
Read_from_file(data.getData().getPath());
}
}
}
public void ReadBtn(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, CHOOSE_TXT_FROM_DEVICE);
}
public void Read_from_file(String file_path) {
File fileMedia = new File(file_path);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_WRITE_STORAGE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, PERMISSION_READ_EXTERNAL_STORAGE);
}
try {
FileInputStream fileIn = openFileInput(fileMedia.getName());
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = InputRead.read(inputBuffer)) > 0) {
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
You didn't attach anything. You could also just post a snippet:
[code]in.read(buf);[/code]
Renate said:
You didn't attach anything. You could also just post a snippet:
Code:
in.read(buf);
Click to expand...
Click to collapse
I have pasted the code...
Please use [code="java"] [/code] markup syntax. I can't read gobble-dee-gook.
Spoiler: Original code
Java:
package android.ble.internal_storage;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
private static final int PERMISSION_WRITE_STORAGE = 11;
private static final int PERMISSION_READ_EXTERNAL_STORAGE = 12;
private static final int CHOOSE_TXT_FROM_DEVICE = 1;
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg = (EditText) findViewById(R.id.editText1);
}
public void WriteBtn(View v) {
try {
FileOutputStream fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE); //mytextfile.txt
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
Context context = getApplicationContext();
String folder = context.getFilesDir().getAbsolutePath();
outputWriter.write(folder + " ");
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_TXT_FROM_DEVICE && resultCode == Activity.RESULT_OK) {
if (data != null) {
Read_from_file(data.getData().getPath());
}
}
}
public void ReadBtn(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, CHOOSE_TXT_FROM_DEVICE);
}
public void Read_from_file(String file_path) {
File fileMedia = new File(file_path);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_WRITE_STORAGE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, PERMISSION_READ_EXTERNAL_STORAGE);
}
try {
FileInputStream fileIn = openFileInput(fileMedia.getName());
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = InputRead.read(inputBuffer)) > 0) {
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem is that your intent.getData() is returning a content URI, not a file URI. There is no path.
https://developer.android.com/reference/android/content/Intent#ACTION_GET_CONTENT
https://developer.android.com/reference/android/content/ContentResolver#openInputStream(android.net.Uri)
Java:
Uri uri = intent.getData();
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(uri);
Renate said:
Please use
Java:
markup syntax. I can't read gobble-dee-gook.
Spoiler: Original code
Java:
package android.ble.internal_storage;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
private static final int PERMISSION_WRITE_STORAGE = 11;
private static final int PERMISSION_READ_EXTERNAL_STORAGE = 12;
private static final int CHOOSE_TXT_FROM_DEVICE = 1;
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg = (EditText) findViewById(R.id.editText1);
}
public void WriteBtn(View v) {
try {
FileOutputStream fileout = openFileOutput("mytextfile.txt", MODE_PRIVATE); //mytextfile.txt
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
Context context = getApplicationContext();
String folder = context.getFilesDir().getAbsolutePath();
outputWriter.write(folder + " ");
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOOSE_TXT_FROM_DEVICE && resultCode == Activity.RESULT_OK) {
if (data != null) {
Read_from_file(data.getData().getPath());
}
}
}
public void ReadBtn(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, CHOOSE_TXT_FROM_DEVICE);
}
public void Read_from_file(String file_path) {
File fileMedia = new File(file_path);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_WRITE_STORAGE);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, PERMISSION_READ_EXTERNAL_STORAGE);
}
try {
FileInputStream fileIn = openFileInput(fileMedia.getName());
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = InputRead.read(inputBuffer)) > 0) {
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem is that your intent.getData() is returning a content URI, not a file URI. There is no path.
https://developer.android.com/reference/android/content/Intent#ACTION_GET_CONTENT
https://developer.android.com/reference/android/content/ContentResolver#openInputStream(android.net.Uri)
Java:
Uri uri = intent.getData();
ContentResolver cr = getContentResolver();
InputStream in = cr.openInputStream(uri);
Click to expand...
Click to collapse
Thank you so much for your help now code is working

Categories

Resources