Pausing thread on ExitDialog - java

What should I do to call thread's pause() method from showExitDialog() here ?
Here's Start Game class
package game.mainmenu;
import game.view.ViewPanel;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
public class StartGame extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );
setContentView(new ViewPanel(this));
}
#Override
protected void onPause() {
super.onPause();
//saveScores();
this.finish();
System.exit(1);// pause game when Activity pauses
}
#Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
if (pKeyCode == KeyEvent.KEYCODE_BACK
&& pEvent.getAction() == KeyEvent.ACTION_DOWN) {
showExitDialog();
return true;
}
return super.onKeyDown(pKeyCode, pEvent);
}
public void showExitDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(StartGame.this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setTitle("EXIT")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
StartGame.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
//alert.setIcon(android.R.drawable.star_on);
alert.show();
}
}
Here's class with main thread
public class ViewManager extends Thread
{
//some states here
public static final int STATE_LOSE = 1;
public static final int STATE_PAUSE = 2;
public static final int STATE_READY = 3;
public static final int STATE_RUNNING = 4;
public static final int STATE_WIN = 5;
//..some not mention code here../
public ViewManager(SurfaceHolder surfaceHolder, Context context)
{
mSurfaceHolder = surfaceHolder;
mRunning = false;
mHealthBar = new Rect(0,0,0,0);
mLinePaint = new Paint();
mLinePaint.setAntiAlias(true);
mLinePaint.setARGB(255, 0, 255, 0);
mLinePaint.setTextSize(16);
mLinePaint.setStrokeWidth(3);
mContext = context;
Resources res = context.getResources();
//..some not mention code here../
InitElements(res);
mHero = new PlayerAnimated(mPlayerImage, FIELD_WIDTH/2, 600, 64, 64, 3, 3, context, mEnemiesList);
//mBoom = new Explosion(mExplosionImage, 200, 500, 64, 64, 7, 7);
mEnemyImage = BitmapFactory.decodeResource(res, R.drawable.enemyone);
setState(STATE_RUNNING);
}
/**
* threads state
* #param running
*/
public void setRunning(boolean running)
{
mRunning = running;
}
//..some not mention code here../
public void run()
{
while (mRunning)
{
Canvas canvas = null;
try
{
// подготовка Canvas-а
canvas = mSurfaceHolder.lockCanvas();
synchronized (mSurfaceHolder)
{
if(mMode == STATE_RUNNING){
// draw if not paused
addEneimes(mContext);
updateStuff();
doDraw(canvas);
}
else
{
pauseDraw(canvas);
}
ViewPanel.displayFps(canvas, aString);
aString = Integer.toString(hudscore.getScore());
}
}
catch (Exception e) { }
finally
{
if (canvas != null)
{
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
//..some not mention code here../
public void pause() {
synchronized (mSurfaceHolder) {
setState(STATE_PAUSE);
mLastFiredTime = System.currentTimeMillis() + 100;
}
}
public void unpause() {
//
synchronized (mSurfaceHolder) {
setState(STATE_RUNNING);
mLastFiredTime = System.currentTimeMillis() + 100;
}
}
public void setState(int mode)
{
mMode = mode;
}
public void pauseDraw(Canvas canvas)
{
canvas.drawBitmap(Bitmap.createBitmap(FIELD_WIDTH, FIELD_HEIGHT, Bitmap.Config.RGB_565), 0, 0, null);
}
}

Not really a clear question, since you are not telling us where you want to create and start the Thread in the main code. Let's assume it's inside onCreate:
public class StartGame extends Activity {
private ViewManager viewManager = new ViewManager();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );
setContentView(new ViewPanel(this));
viewManager.start(); // start viewManager thread
}
// other methods
public void showExitDialog() {
viewManager.pause(); // call pause
// rest of code
}
}

Related

Why does my Java code for Android App Generate 2 threads?

I am new to Java coding for android. I need to understand why does my code generate 2 threads. The problem that can be created over here is perhaps competition for Camera Resources which results in the camera not being used by the user. Kindly suggest a solution to my problem as well.
I have also attached a picture where there are 2 requests for a new activity. There is also proof by having 2 thread IDs active.
EDIT for clarity:
I want to generate a new thread which solely handles the activity to record the video, no other thread should be doing it. But there are two that are performing their own activity to record video.
public class MainActivity extends AppCompatActivity implements SensorEventListener/*, ActivityCompat.OnRequestPermissionsResultCallback*/ {
private Camera c;
private MainActivity reference_this = this;
private BooleanObject recorded_video = new BooleanObject("recorded_video",false);
private BooleanObject recorded_motions_chest = new BooleanObject("recorded_motions_chest", false);
private ChangeListener listener_change;
public void setListener(ChangeListener arg_listener_change) {
listener_change = arg_listener_change;
}
public interface ChangeListener {
void onChange(String arg_name);
}
public void set_recorded_video(boolean arg_recorded_video) {
recorded_video.set_value(arg_recorded_video);
if (listener_change != null) { listener_change.onChange(recorded_video.get_name()); }
}
public void set_recorded_motions_chest(boolean arg_recorded_motions_chest) {
recorded_motions_chest.set_value(arg_recorded_motions_chest);
if (listener_change != null) { listener_change.onChange(recorded_motions_chest.get_name()); }
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))) {
this.finish();
System.exit(0);
}
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
this.setListener(new MainActivity.ChangeListener() {
#Override
public void onChange(String arg_name) {
Log.i("CHNG", "fired");
if (arg_name.equals(recorded_video.get_name())) {
VideoCapture video_capture = new VideoCapture();
video_capture.open(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
Mat frame = new Mat();
int length_video = (int) video_capture.get(Videoio.CAP_PROP_FRAME_COUNT);
int rate_frame = (int) video_capture.get(Videoio.CAP_PROP_FPS);
while (true) {
video_capture.read(frame);
Size size_img = frame.size();
Log.i("MAT", String.valueOf(size_img.width) + ' ' + String.valueOf(size_img.height));
}
}
else if (arg_name.equals(recorded_motions_chest.get_name())) {}
}
});
// new Thread(new Runnable() {
// public void run() {
Button button_symptoms = (Button) findViewById(R.id.button_symptoms);
Button button_upload_signs = (Button) findViewById(R.id.button_upload_signs);
Button button_measure_heart_rate = (Button) findViewById(R.id.button_measure_heart_rate);
Button button_measure_respiratory_rate = (Button) findViewById(R.id.button_measure_respiratory_rate);
CameraView cv1 = new CameraView(getApplicationContext(), reference_this);
FrameLayout view_camera = (FrameLayout) findViewById(R.id.view_camera);
view_camera.addView(cv1);
TextView finger_on_sensor = (TextView) findViewById(R.id.text_finger_on_sensor);
finger_on_sensor.setVisibility(View.INVISIBLE);
finger_on_sensor.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch (View arg_view, MotionEvent arg_me){
finger_on_sensor.setVisibility(View.INVISIBLE);
/*GENERATING THREADS OVER HERE*/ new Thread(new Runnable() {
public void run() {
File file_video = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
// final int REQUEST_WRITE_PERMISSION = 786;
final int VIDEO_CAPTURE = 1;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45);
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cse535a1.provider", file_video);
intent_record_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
if (intent_record_video.resolveActivity(getPackageManager()) != null) {
Log.i("CAM", "CAM requeted");
Log.i("Thread ID", String.valueOf(Thread.currentThread().getId()));
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
// reference_this.set_recorded_video(true);
}
}
}).start();
return true;
}
});
button_symptoms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){
Intent intent = new Intent(getApplicationContext(), Loggin_symptoms.class);
startActivity(intent);
}
});
button_upload_signs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){
}
});
button_measure_heart_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View arg_view){ finger_on_sensor.setVisibility(View.VISIBLE); }
});
button_measure_respiratory_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg_view) {
SensorManager manager_sensor = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor_accelerometer = manager_sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
manager_sensor.registerListener(MainActivity.this, sensor_accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
});
// }}).start();
}
public void setCam(Camera arg_camera) { c = arg_camera; }
#Override
public void onSensorChanged(SensorEvent arg_event) {
float x = arg_event.values[0];
float y = arg_event.values[1];
float z = arg_event.values[2];
Log.i("ACCELEROMETER", String.valueOf(x) + ' ' + String.valueOf(y) + ' ' + String.valueOf(z));
}
#Override
public void onAccuracyChanged(Sensor arg_sensor, int arg_accuracy) {
}
#Override
protected void onPause() {
super.onPause();
c.unlock();
// Log.i("CAM", "unlocked");
// if (c != null) {
// c.stopPreview();
//// c.release();
//// c = null;
// }
}
#Override
protected void onResume() {
super.onResume();
if (c != null) c.lock();
// if (c != null) {
// c.stopPreview();
// c.release();
// c = null;
/// }
// cv1 = new CameraView(getApplicationContext(), this);
// view_camera.addView(cv1);
}
#Override
protected void onDestroy() {
if (c != null) {
// c.unlock();
c.stopPreview();
c.release();
c = null;
}
super.onDestroy();
}
private static class BooleanObject {
private String name = "BooleanObject";
private boolean value = false;
public BooleanObject(String arg_name, boolean arg_value) {
name = arg_name;
value = arg_value;
}
public String set_name(String arg_name) {
name = arg_name;
return name;
}
public boolean set_value(boolean arg_value) {
value = arg_value;
return value;
}
public String get_name() { return name; }
public boolean get_value() { return value; }
};
}
Every time you tap on TextView, as you are using onTouchListener, it will be fired twice, once for ACTION_DOWN and ACTION_UP, so check for ACTION_UP as in
finger_on_sensor.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch (View arg_view, MotionEvent arg_me){
if(arg_me.getAction() == MotionEvent.ACTION_UP){ //add this condition
finger_on_sensor.setVisibility(View.INVISIBLE);
new Thread(new Runnable() {
public void run() {
File file_video = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/video_finger.mp4");
// final int REQUEST_WRITE_PERMISSION = 786;
final int VIDEO_CAPTURE = 1;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent intent_record_video = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent_record_video.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 45);
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cse535a1.provider", file_video);
intent_record_video.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
if (intent_record_video.resolveActivity(getPackageManager()) != null) {
Log.i("CAM", "CAM requeted");
Log.i("Thread ID", String.valueOf(Thread.currentThread().getId()));
startActivityForResult(intent_record_video, VIDEO_CAPTURE);
//reference_this.set_recorded_video(true);
}
}
}).start();
return true;
}
});

How can a View react to a Method call of a SurfaceView?

RESUME
I'm programming a pacman, it is almost done but I'm having problems with the communication between the view which will show the score and the currect direction of the pacman, and the surface view which will draw the game.
The PlayActivity (which is an AppCompatActivity) has a GameView(which is a SurfaceView where the game is draw) and knows the GameManager(a class I've made that basically knows the pacman, the map, the ghosts, and everything). The PlayActivity also has a text view called scoreTv. I don't know how to update this text view.
The idea is that the scoreTv change its text value whenever the GameManager's methods addScore(int),eatPallet(int, int), eatBonus(int,int); eatSuperPallet(int,int) are invoked.
Here is the PlayActivity code
package Activities;
import android.os.Bundle;
import android.view.SurfaceView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.pacman.DBManager;
import Game.GameView;
import com.example.pacman.R;
import com.example.pacman.Score;
public class PlayActivity extends AppCompatActivity {
private TextView playerNickname;
TextView score;
private TextView maxScore;
private SurfaceView gameSurfaceView;
private GameView gameView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Modified code
setContentView(R.layout.activity_game);
//we get text view that we will use
playerNickname=(TextView) this.findViewById(R.id.tv_player);
score=(TextView) this.findViewById(R.id.tv_current_score);
maxScore=(TextView) this.findViewById(R.id.tv_current_max_score);
gameSurfaceView= (GameView) this.findViewById(R.id.game_view);
//set text view initial values
playerNickname.setText(getIntent().getExtras().getString("playerNickname"));
score.setText("0");
maxScore.setText("To modify");
this.gameView=new GameView(gameSurfaceView.getContext());
this.gameSurfaceView.getHolder().addCallback(this.gameView);
}
protected void onResume(){
super.onResume();
this.gameView.resume();
}
protected void onPause(){
super.onPause();
this.gameView.pause();
}
public void updateScore(int score){
this.score.setText(""+score);
}
public void onLose(double score){
//We try to save the score, if there is a previous register we write only if this score
//is better that the one before
DBManager manager;
long raw;
Score scoreToSave;
manager=new DBManager(this);
scoreToSave=new Score(this.playerNickname.toString(), score);
if(manager.saveScore(scoreToSave)==-1){
//if i couldn't save the score
if(manager.updateScore(scoreToSave)!=-1){
//if my new score is better than the one previous
}else{
//if my new score is worse or equal than the one previous
}
}
}
}
And here is the Game View code
package Game;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import Activities.PlayActivity;
import Game.Character_package.Ghost;
import Game.Character_package.Pacman;
public class GameView extends SurfaceView implements Runnable, SurfaceHolder.Callback, GestureDetector.OnGestureListener {
private static final float SWIPE_THRESHOLD = 2;
private static final float SWIPE_VELOCITY = 2;
private boolean GHOST_INICIALIZED=false;
private GestureDetector gestureDetector;
private GameManager gameManager;
private Thread thread; //game thread
private SurfaceHolder holder;
private boolean canDraw = false;
private int blockSize; // Ancho de la pantalla, ancho del bloque
private static int movementFluencyLevel=8; //this movement should be a multiple of the blocksize and multiple of 4, if note the pacman will pass walls
private int totalFrame = 4; // Cantidad total de animation frames por direccion
private int currentArrowFrame = 0; // animation frame de arrow actual
private long frameTicker; // tiempo desde que el ultimo frame fue dibujado
//----------------------------------------------------------------------------------------------
//Constructors
public GameView(Context context) {
super(context);
this.constructorHelper(context);
}
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
this.constructorHelper(context);
}
public GameView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.constructorHelper(context);
}
private void constructorHelper(Context context) {
this.gestureDetector = new GestureDetector(this);
this.setFocusable(true);
this.holder = getHolder();
this.holder.addCallback(this);
this.frameTicker = (long) (1000.0f / totalFrame);
this.gameManager=new GameManager(this);
int screenWidth=getResources().getDisplayMetrics().widthPixels;
this.blockSize = ((((screenWidth/this.gameManager.getGameMap().getMapWidth())/movementFluencyLevel)*movementFluencyLevel)/4)*4;
this.holder.setFixedSize(blockSize*this.gameManager.getGameMap().getMapWidth(),blockSize*this.gameManager.getGameMap().getMapHeight());
this.gameManager.getGameMap().loadBonusBitmaps(this);
this.gameManager.setPacman(new Pacman("pacman","",this,this.movementFluencyLevel));
Ghost.loadCommonBitmaps(this);
}
//----------------------------------------------------------------------------------------------
//Getters and setters
public int getBlockSize() {
return blockSize;
}
public GameManager getGameManager() {
return gameManager;
}
public int getMovementFluencyLevel(){return movementFluencyLevel;}
//----------------------------------------------------------------------------------------------
private synchronized void initGhost(){
if(!GHOST_INICIALIZED){
GHOST_INICIALIZED=true;
this.gameManager.initGhosts(this);
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void run() {
long gameTime;
Canvas canvas;
while (!holder.getSurface().isValid()) {
}
this.initGhost();
this.setFocusable(true);
while (canDraw) {
gameTime=System.currentTimeMillis();
if(gameTime > frameTicker + (totalFrame * 15)){
canvas = holder.lockCanvas();
if(canvas!=null){
if(this.updateFrame(gameTime,canvas)){
try {
Thread.sleep(3000);
}catch (Exception e){}
}
holder.unlockCanvasAndPost(canvas);
if(this.gameManager.checkWinLevel()){
canDraw=false;
this.gameManager.cancelThreads();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
//animation
Log.i("Game","You win");
}else if(!this.gameManager.getPacman().hasLifes()){
//we lost
canDraw=false;
this.gameManager.cancelThreads();
//animation
Log.i("Game","You lose");
}
}
}
}
}
// Method to capture touchEvents
#Override
public boolean onTouchEvent(MotionEvent event) {
//To swipe
//https://www.youtube.com/watch?v=32rSs4tE-mc
this.gestureDetector.onTouchEvent(event);
super.onTouchEvent(event);
return true;
}
//Chequea si se deberia actualizar el frame actual basado en el
// tiempo que a transcurrido asi la animacion
//no se ve muy rapida y mala
#RequiresApi(api = Build.VERSION_CODES.N)
private boolean updateFrame(long gameTime, Canvas canvas) {
Pacman pacman;
Ghost[] ghosts;
boolean pacmanIsDeath;
pacman=this.gameManager.getPacman();
ghosts=this.gameManager.getGhosts();
// Si el tiempo suficiente a transcurrido, pasar al siguiente frame
frameTicker = gameTime;
canvas.drawColor(Color.BLACK);
this.gameManager.getGameMap().draw(canvas, Color.BLUE,this.blockSize,this.gameManager.getLevel());
this.gameManager.moveGhosts(canvas,this.blockSize);
pacmanIsDeath=pacman.move(this.gameManager,canvas);
if(!pacmanIsDeath){
// incrementar el frame
pacman.changeFrame();
for(int i=0; i<ghosts.length;i++){
ghosts[i].changeFrame();
}
currentArrowFrame++;
currentArrowFrame%=7;
}else{
pacman.setNextDirection(' ');
for(int i=0; i<ghosts.length;i++){
ghosts[i].respawn();
}
}
return pacmanIsDeath;
}
//----------------------------------------------------------------------------------------------
//Callback methods
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void surfaceCreated(SurfaceHolder holder) {
canDraw = true;
this.thread= new Thread(this);
this.thread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
//----------------------------------------------------------------------------------------------
public void resume() {
this.canDraw = true;
thread = new Thread(this);
thread.start();
}
public void pause() {
this.canDraw = false;
while (true) {
try {
thread.join();
return;
} catch (InterruptedException e) {
// retry
}
break;
}
this.thread=null;
}
#Override
public boolean onDown(MotionEvent e) {
return false;
}
#Override
public void onShowPress(MotionEvent e) {
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
#Override
public void onLongPress(MotionEvent e) {
}
#Override
public boolean onFling(MotionEvent downEvent, MotionEvent moveEvent, float velocityX, float velocityY) {
//To swipe
//https://www.youtube.com/watch?v=32rSs4tE-mc
float diffX, diffY;
Pacman pacman;
Log.i("Fling", "detected");
diffX = moveEvent.getX() - downEvent.getX();
diffY = moveEvent.getY() - downEvent.getY();
pacman=this.gameManager.getPacman();
if (Math.abs(diffX) > Math.abs(diffY)) {
//right or left swipe
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY) {
if (diffX > 0) {
//right
pacman.setNextDirection('r');
} else {
//left
pacman.setNextDirection('l');
}
}
} else {
//up or down swipe
if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY) {
if (diffY > 0) {
//down
pacman.setNextDirection('d');
} else {
//up
pacman.setNextDirection('u');
}
}
}
return true;
}
}
And finally the GameManager code
package Game;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.util.Log;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import com.example.pacman.R;
import org.jetbrains.annotations.NotNull;
import Game.Behavior.ChaseBehavior.*;
import Game.Character_package.Ghost;
import Game.Character_package.Pacman;
import Game.GameCountDown.*;
public class GameManager {
private static final int TOTAL_LEVELS=256;
private GameMap gameMap;
private int level,bonusResetTime,score;
private CountDownScareGhosts scareCountDown;
private Pacman pacman;
private Ghost[] ghosts;
private boolean fruitHasBeenInTheLevel;
public GameManager(GameView gameView){
this.fruitHasBeenInTheLevel=false;
this.score=0;
this.gameMap=new GameMap();
this.gameMap.loadMap1();
this.level=1;
this.ghosts=new Ghost[4];
this.bonusResetTime = 5000;
this.scareCountDown=null;
}
public void addScore(int s){
this.score+=s;
}
public int getScore() {
return this.score;
}
public int getLevel() {
return this.level;
}
public GameMap getGameMap() {
return this.gameMap;
}
public Ghost[] getGhosts(){
return this.ghosts;
}
public Ghost getGhost(int i) {
return this.ghosts[i];
}
public Pacman getPacman(){
return this.pacman;
}
public void setPacman(Pacman pacman){
this.pacman=pacman;
}
public void eatPallet(int posXMap, int posYMap){
this.score+=10;
//Log.i("Score", Double.toString(this.score).substring(0,Double.toString(this.score).indexOf('.')));
this.gameMap.getMap()[posYMap][posXMap]=0;
}
public void eatBonus(int posXMap,int posYMap){
this.score+=500;
//Log.i("Score", Double.toString(this.score).substring(0,Double.toString(this.score).indexOf('.')));
this.gameMap.getMap()[posYMap][posXMap]=0;
}
public void eatSuperPallet(int posXMap,int posYMap){
this.score+=50;
Log.i("Score", Double.toString(this.score).substring(0,Double.toString(this.score).indexOf('.')));
this.gameMap.getMap()[posYMap][posXMap]=0;
//Si hay un timer andando lo cancelo y ejecuto otro
if (this.scareCountDown != null){
this.scareCountDown.cancel();
}
this.scareCountDown = new CountDownScareGhosts(this.ghosts,this.gameMap.getMap());
this.scareCountDown.start();
}
public void tryCreateBonus(){
//only if pacman has eaten 20 pallets we should allow the fruit appear
if(!this.fruitHasBeenInTheLevel && this.gameMap.getEatenPallets()>=20){
//to not allow the fruit be again in the level
this.fruitHasBeenInTheLevel=true;
new CountdownBonusThread(this.gameMap,this.bonusResetTime).start();
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
public void moveGhosts(Canvas canvas,int blocksize) {
for (int i = 0; i < ghosts.length; i++) {
ghosts[i].move(this.gameMap.getMap(),this.pacman);
ghosts[i].draw(canvas);
}
}
public synchronized void initGhosts(#NotNull GameView gv) {
int[][]spawnPositions,cornersPositions, notUpDownPositions,defaultTargets;
int movementeFluency;
defaultTargets=this.gameMap.getDefaultGhostTarget();
notUpDownPositions=this.gameMap.getNotUpDownDecisionPositions();
spawnPositions=this.gameMap.getGhostsSpawnPositions();
cornersPositions=this.gameMap.getGhostsScatterTarget();
movementeFluency=gv.getMovementFluencyLevel();
//start position
// 5 blinky spawn [13, 11]
// 6 pinky spawn [15,11]
// 7 inky spawn [13,16]
// 8 clyde spawn [15,16]
this.ghosts=new Ghost[4];
ghosts[0] = new Ghost("blinky",gv,spawnPositions[0], cornersPositions[0] ,new BehaviorChaseAgressive(notUpDownPositions,movementeFluency,defaultTargets[0]),movementeFluency,notUpDownPositions,'l',defaultTargets[0]);
ghosts[1] = new Ghost("pinky",gv,spawnPositions[1],cornersPositions[1],new BehaviorChaseAmbush(notUpDownPositions,movementeFluency,defaultTargets[1]),movementeFluency,notUpDownPositions,'r',defaultTargets[1]);
ghosts[2] = new Ghost("inky",gv,spawnPositions[2],cornersPositions[2],new BehaviorChasePatrol(notUpDownPositions,this.ghosts[0],movementeFluency,defaultTargets[0]),movementeFluency,notUpDownPositions,'l',defaultTargets[0]);
ghosts[3] = new Ghost("clyde",gv,spawnPositions[3],cornersPositions[3],new BehaviorChaseRandom(notUpDownPositions,cornersPositions[3],movementeFluency,defaultTargets[1]),movementeFluency,notUpDownPositions,'r',defaultTargets[1]);
try{
Thread.sleep(200);
}catch(Exception e){}
for (int i=0;i<ghosts.length;i++){
ghosts[i].onLevelStart(1);
}
}
public boolean checkWinLevel() {
//player win the level if he has eaten all the pallet
return this.gameMap.countPallets()==0;
}
public void onResume(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null && !this.scareCountDown.hasEnded()){
this.scareCountDown.start();
}
}
public void onPause(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null && !this.scareCountDown.hasEnded()){
this.scareCountDown=this.scareCountDown.onPause();
}
}
public void cancelThreads(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null){
this.scareCountDown.cancel();
}
}
}
What I know so far is that I can't sent the scoreTv to the GameView, because the GameView can't change it due to not being in the same thread. I need the PlayActivity instance react whenever any of the methods I've told you before are called.
Well, I have found a solution, I don't like it, tough.
What have I done is the next:
I have created a STATIC SEMAPHORE in the AppCompatActivity
I pass it to the class GameManager as a STATIC SEMAPHORE too and I've changed the score in this class to static
Finally I've run a thread in the PlayActivity with the method runOnUiThread to update the scoreTv, this thread will acquire a permit, this one will be relese whenever the SCORE is update in the GameManager to avoid the active wait
You may be asking why I remark STATIC. If I don't do this, I don't know why the reference of the GameManager get lost. If someone know the answer please post it.
Here a link to the git repo, and here the code of the classes
public class PlayActivity extends AppCompatActivity {
private TextView playerNickname;
private TextView scoreTv;
private TextView maxScore;
private SurfaceView gameSurfaceView;
private GameView gameView;
private GameManager gameManager;
private static Semaphore CHANGE_SCORE_MUTEX=new Semaphore(0,true);
private static Semaphore CHANGE_DIRECTION_MUTEX=new Semaphore(0,true);
private Thread changeScoreThread, changeDirectionThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Modified code
setContentView(R.layout.activity_game);
//we get text view that we will use
playerNickname=(TextView) this.findViewById(R.id.tv_player);
scoreTv=(TextView) this.findViewById(R.id.tv_current_score);
maxScore=(TextView) this.findViewById(R.id.tv_current_max_score);
gameSurfaceView= (GameView) this.findViewById(R.id.game_view);
//set text view initial values
playerNickname.setText(getIntent().getExtras().getString("playerNickname"));
scoreTv.setText("0");
maxScore.setText("To modify");
this.gameView=new GameView(gameSurfaceView.getContext());
this.gameManager=this.gameView.getGameManager();
this.gameView.setSemaphores(CHANGE_SCORE_MUTEX,CHANGE_DIRECTION_MUTEX);
this.gameSurfaceView.getHolder().addCallback(this.gameView);
}
protected void onResume(){
super.onResume();
this.gameView.resume();
this.initChangerThreads();
}
public void updateScoreTv(int score){
this.scoreTv.setText(""+score);
}
protected void onPause(){
super.onPause();
this.gameView.pause();
//in order to stop the threads
CHANGE_SCORE_MUTEX.release();
CHANGE_DIRECTION_MUTEX.release();
}
public void onLose(double score){
//We try to save the score, if there is a previous register we write only if this score
//is better that the one before
DBManager manager;
long raw;
Score scoreToSave;
manager=new DBManager(this);
scoreToSave=new Score(this.playerNickname.toString(), score);
if(manager.saveScore(scoreToSave)==-1){
//if i couldn't save the score
if(manager.updateScore(scoreToSave)!=-1){
//if my new score is better than the one previous
}else{
//if my new score is worse or equal than the one previous
}
}
}
private void initChangerThreads() {
this.changeScoreThread = new Thread(new Runnable() {
public void run() {
while (gameView.isDrawing()) {
//Log.i("Score ",""+gameManager.getScore());
try {
CHANGE_SCORE_MUTEX.acquire();
runOnUiThread(new Runnable() {
#Override
public void run() {
updateScoreTv(gameView.getGameManager().getScore());
}
});
}catch (Exception e){}
}
}
});
this.changeScoreThread.start();
}
}
GameView: I've just added this method
public void setSemaphores(Semaphore changeScoreSemaphore, Semaphore changeDirectionSemaphore){
this.gameManager.setChangeScoreSemaphore(changeScoreSemaphore);
this.gameManager.getPacman().setChangeDirectionSemaphore(changeDirectionSemaphore);
Log.i("Semaphore", "setted");
}
GameManager
public class GameManager {
private static final int TOTAL_LEVELS=256;
private static int SCORE=0;
private GameMap gameMap;
private int level,bonusResetTime;//,score;
private CountDownScareGhosts scareCountDown;
private Pacman pacman;
private Ghost[] ghosts;
private boolean fruitHasBeenInTheLevel;
private static Semaphore CHANGE_SCORE_MUTEX;
public GameManager(){
this.fruitHasBeenInTheLevel=false;
//this.score=0;
this.gameMap=new GameMap();
this.gameMap.loadMap1();
this.level=1;
this.ghosts=new Ghost[4];
this.bonusResetTime = 5000;
this.scareCountDown=null;
}
public void setChangeScoreSemaphore(Semaphore changeScoreSemaphore) {
CHANGE_SCORE_MUTEX = changeScoreSemaphore;
//if(this.changeScoreSemaphore==null){
// Log.i("Change Score Semaphore","I'm null");
//}else{
// Log.i("Change Score Semaphore","I'm not null");
//}
}
public void addScore(int s){
//this.score+=s;
SCORE+=s;
CHANGE_SCORE_MUTEX.release();
/*if(this.changeScoreSemaphore==null){
Log.i("Change Score Semaphore","I'm null");
}else{
Log.i("Change Score Semaphore","I'm not null");
}*/
//this.changeScoreSemaphore.release();
}
public int getScore() {
return SCORE;
//return this.score;
}
public int getLevel() {
return this.level;
}
public GameMap getGameMap() {
return this.gameMap;
}
public Ghost[] getGhosts(){
return this.ghosts;
}
public Pacman getPacman(){
return this.pacman;
}
public void setPacman(Pacman pacman){
this.pacman=pacman;
}
public void eatPallet(int posXMap, int posYMap){
SCORE+=10;
CHANGE_SCORE_MUTEX.release();
//this.score+=10;
Log.i("Score GM", ""+SCORE);
//Log.i("Score GM", ""+this.score);
this.gameMap.getMap()[posYMap][posXMap]=0;
//this.changeScoreSemaphore.release();
//if(this.changeScoreSemaphore==null){
// Log.i("Change Score Semaphore","I'm null");
//}else{
// Log.i("Change Score Semaphore","I'm not null");
//}
}
public void eatBonus(int posXMap,int posYMap){
SCORE+=500;
CHANGE_SCORE_MUTEX.release();
//this.score+=500;
//Log.i("Score", Double.toString(this.score).substring(0,Double.toString(this.score).indexOf('.')));
this.gameMap.getMap()[posYMap][posXMap]=0;
//this.changeScoreSemaphore.release();
}
public void eatSuperPallet(int posXMap,int posYMap){
SCORE+=50;
CHANGE_SCORE_MUTEX.release();
//this.score+=50;
this.gameMap.getMap()[posYMap][posXMap]=0;
//Si hay un timer andando lo cancelo y ejecuto otro
if (this.scareCountDown != null){
this.scareCountDown.cancel();
}
this.scareCountDown = new CountDownScareGhosts(this.ghosts,this.gameMap.getMap());
this.scareCountDown.start();
//this.changeScoreSemaphore.release();
}
public void tryCreateBonus(){
//only if pacman has eaten 20 pallets we should allow the fruit appear
if(!this.fruitHasBeenInTheLevel && this.gameMap.getEatenPallets()>=20){
//to not allow the fruit be again in the level
this.fruitHasBeenInTheLevel=true;
new CountdownBonusThread(this.gameMap,this.bonusResetTime).start();
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
public void moveGhosts(Canvas canvas,int blocksize) {
for (int i = 0; i < ghosts.length; i++) {
ghosts[i].move(this.gameMap.getMap(),this.pacman);
ghosts[i].draw(canvas);
}
}
public synchronized void initGhosts(int blocksize, Resources res, String packageName,int movementFluency) {
int[][]spawnPositions,cornersPositions, notUpDownPositions,defaultTargets;
defaultTargets=this.gameMap.getDefaultGhostTarget();
notUpDownPositions=this.gameMap.getNotUpDownDecisionPositions();
spawnPositions=this.gameMap.getGhostsSpawnPositions();
cornersPositions=this.gameMap.getGhostsScatterTarget();
//start position
// 5 blinky spawn [13, 11]
// 6 pinky spawn [15,11]
// 7 inky spawn [13,16]
// 8 clyde spawn [15,16]
this.ghosts=new Ghost[4];
ghosts[0] = new Ghost("blinky",spawnPositions[0], cornersPositions[0] ,new BehaviorChaseAgressive(notUpDownPositions,movementFluency,defaultTargets[0]),movementFluency,notUpDownPositions,'l',defaultTargets[0],blocksize,res,packageName);
ghosts[1] = new Ghost("pinky",spawnPositions[1],cornersPositions[1],new BehaviorChaseAmbush(notUpDownPositions,movementFluency,defaultTargets[1]),movementFluency,notUpDownPositions,'r',defaultTargets[1],blocksize,res,packageName);
ghosts[2] = new Ghost("inky",spawnPositions[2],cornersPositions[2],new BehaviorChasePatrol(notUpDownPositions,this.ghosts[0],movementFluency,defaultTargets[0]),movementFluency,notUpDownPositions,'l',defaultTargets[0],blocksize,res,packageName);
ghosts[3] = new Ghost("clyde",spawnPositions[3],cornersPositions[3],new BehaviorChaseRandom(notUpDownPositions,cornersPositions[3],movementFluency,defaultTargets[1]),movementFluency,notUpDownPositions,'r',defaultTargets[1],blocksize,res,packageName);
try{
Thread.sleep(200);
}catch(Exception e){}
for (int i=0;i<ghosts.length;i++){
ghosts[i].onLevelStart(1);
}
}
public boolean checkWinLevel() {
//player win the level if he has eaten all the pallet
return this.gameMap.countPallets()==0;
}
public void onResume(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null && !this.scareCountDown.hasEnded()){
this.scareCountDown.start();
}
}
public void onPause(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null && !this.scareCountDown.hasEnded()){
this.scareCountDown=this.scareCountDown.onPause();
}
}
public void cancelThreads(){
for (int i=0 ; i<this.ghosts.length;i++){
this.ghosts[i].cancelBehavoirThread();
}
if(this.scareCountDown!=null){
this.scareCountDown.cancel();
}
}
}
I haven't found a solution like this anywhere, I wish I've save you a lot of research time if you're currently having a problem like this :D

Merge Android Studio activities

I am having a problem with merging two activities in Android Studio. I am new to coding and I know this should be relatively simple but I am slowly learning, so bear with me.
Basically my starting activity was a sample app that came with the IOIO development board. I have modified this to work for my application. I also have a MAX31855 thermocouple amplifier that I have found code for and it is working perfect, the only problem is that all of the code is in a separate activity from my sample app activity. So both will not run at the same time on my simple one screen app. So now I am trying to merge the thermocouple amplifier code into the sample app code. How should I start going about this? I have attached the code for both activities below.
The code for the sample app:
package ioio.examples.simple;
import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.IOIO;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import ioio.lib.api.SpiMaster;
import ioio.lib.api.SpiMaster.Rate;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.List;
public class IOIOSimpleApp extends IOIOActivity {
private TextView boost;
private TextView fuelpressure;
private TextView ioioStatusText;
private TextView internalText;
private TextView thermocoupleText;
private TextView faultsText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boost = (TextView) findViewById(R.id.boost);
fuelpressure = (TextView) findViewById(R.id.fuelpressure);
ioioStatusText = (TextView) findViewById(R.id.ioio_status);
internalText = (TextView) findViewById(R.id.internal);
thermocoupleText = (TextView) findViewById(R.id.thermocouple);
faultsText = (TextView) findViewById(R.id.faults);
enableUi(false);
}
class Looper extends BaseIOIOLooper {
private AnalogInput boost, fuelpressure;
#Override
public void setup() throws ConnectionLostException {
boost = ioio_.openAnalogInput(45);
fuelpressure = ioio_.openAnalogInput(42);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
setNumber1(38.314 * ((boost.getVoltage() - 0.27)));
setNumber2(38.314 * ((fuelpressure.getVoltage() - 0.27)));
Thread.sleep(200);
}
#Override
public void disconnected() {
enableUi(false);
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
private void enableUi(final boolean enable) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//seekBar_.setEnabled(enable);
//toggleButton_.setEnabled(enable);
}
});
}
private void setNumber1(double f) {
final String str = String.format("%.0f", f);
runOnUiThread(new Runnable() {
#Override
public void run() {
boost.setText(str);
}
});
}
private void setNumber2(double f) {
final String str = String.format("%.0f", f);
runOnUiThread(new Runnable() {
#Override
public void run() {
fuelpressure.setText(str);
}
});
}
}
And the code for the thermocouple amplifier:
package ioio.examples.simple;
import ioio.lib.api.SpiMaster;
import ioio.lib.api.SpiMaster.Rate;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import ioio.lib.api.AnalogInput;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends IOIOActivity {
protected static final float FAULT_DISPLAY_DURATION = 10; // seconds
private TextView ioioStatusText;
private TextView internalText;
private TextView thermocoupleText;
private TextView faultsText;
private TextView boost;
private TextView fuelpressure;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ioioStatusText = (TextView) findViewById(R.id.ioio_status);
internalText = (TextView) findViewById(R.id.internal);
thermocoupleText = (TextView) findViewById(R.id.thermocouple);
faultsText = (TextView) findViewById(R.id.faults);
boost = (TextView) findViewById(R.id.boost);
fuelpressure = (TextView) findViewById(R.id.fuelpressure);
}
#Override
protected IOIOLooper createIOIOLooper() {
int sdoPin = 1; // DO
int sdaPin = 29; // we do not use this pin but the IOIOLib requires we specify it, so we pick an unused pin
int sclPin = 2; // CLK
int csPin = 3; // CS
Rate rate = SpiMaster.Rate.RATE_31K;
final MAX31855 max31855 = new MAX31855(sdoPin, sdaPin, sclPin, csPin, rate);
max31855.setListener(new MAX31855.MAX31855Listener() {
private long faultTime;
#Override
public void onData(float internal, float thermocouple) {
updateTextView(internalText, "Internal = " + internal + " C");
updateTextView(thermocoupleText, thermocouple + " C");
float secondsSinceFault = (System.nanoTime() - faultTime) / 1000000000.0f;
if (secondsSinceFault > FAULT_DISPLAY_DURATION) {
updateTextView(faultsText, "Faults = ");
}
}
#Override
public void onFault(byte f) {
List<String> faults = new ArrayList<String>();
if ((f & MAX31855.FAULT_OPEN_CIRCUIT_BIT) == MAX31855.FAULT_OPEN_CIRCUIT_BIT)
faults.add("Open Circuit");
if ((f & MAX31855.FAULT_SHORT_TO_GND_BIT) == MAX31855.FAULT_SHORT_TO_GND_BIT)
faults.add("Short To GND");
if ((f & MAX31855.FAULT_SHORT_TO_VCC_BIT) == MAX31855.FAULT_SHORT_TO_VCC_BIT)
faults.add("Short To VCC");
boolean first = true;
String text = "Faults = ";
for (String fault : faults) {
if (!first)
text += ", ";
text += fault;
}
if (faults.size() > 0) {
faultTime = System.nanoTime();
}
updateTextView(faultsText, text);
}
});
return new DeviceLooper(max31855);
}
private void updateTextView(final TextView textView, final String text) {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(text);
}
});
}
/**
* This is the thread on which all the IOIO activity happens. It will be run
* every time the application is resumed and aborted when it is paused. The
* method setup() will be called right after a connection with the IOIO has
* been established (which might happen several times!). Then, loop() will
* be called repetitively until the IOIO gets disconnected.
*/
class DeviceLooper extends BaseIOIOLooper {
private IOIOLooper device;
public DeviceLooper(IOIOLooper device) {
this.device = device;
}
#Override
public void setup() throws ConnectionLostException, InterruptedException {
device.setup(ioio_);
updateTextView(ioioStatusText, "IOIO Connected");
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
device.loop();
}
#Override
public void disconnected() {
device.disconnected();
updateTextView(ioioStatusText, "IOIO Disconnected");
}
#Override
public void incompatible() {
updateTextView(ioioStatusText, "IOIO Incompatible");
}
}
}
I hope this makes sense and I have provided enough information. There is another separate activity for the MAX31855, but I assume this can be left untouched. Again, I am slowly learning how java and android studio works, I just can't seem to figure out how to merge these two activities without having a bunch of errors in the code. Any help is appreciated, thank you!
You need to consider three things.
1) main.xml Layout file in res->layout
2) AndroidManifest.xml in manifest folder
3) Single activity which include all codes.
All components should be initialized from a same activity (in your case MainActivity or IOIOSimpleApp).
Also remember to include all components (what you have initialized from activity) to the main.xml layout.
And try this
public class IOIOSimpleApp extends IOIOActivity {
protected static final float FAULT_DISPLAY_DURATION = 10; // seconds
private TextView boost;
private TextView fuelpressure;
private TextView ioioStatusText;
private TextView internalText;
private TextView thermocoupleText;
private TextView faultsText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boost = (TextView) findViewById(R.id.boost);
fuelpressure = (TextView) findViewById(R.id.fuelpressure);
ioioStatusText = (TextView) findViewById(R.id.ioio_status);
internalText = (TextView) findViewById(R.id.internal);
thermocoupleText = (TextView) findViewById(R.id.thermocouple);
faultsText = (TextView) findViewById(R.id.faults);
//components in main activity
ioioStatusText = (TextView) findViewById(R.id.ioio_status);
internalText = (TextView) findViewById(R.id.internal);
thermocoupleText = (TextView) findViewById(R.id.thermocouple);
faultsText = (TextView) findViewById(R.id.faults);
boost = (TextView) findViewById(R.id.boost);
fuelpressure = (TextView) findViewById(R.id.fuelpressure);
enableUi(false);
}
class Looper extends BaseIOIOLooper {
private AnalogInput boost, fuelpressure;
#Override
public void setup() throws ConnectionLostException {
boost = ioio_.openAnalogInput(45);
fuelpressure = ioio_.openAnalogInput(42);
enableUi(true);
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
setNumber1(38.314 * ((boost.getVoltage() - 0.27)));
setNumber2(38.314 * ((fuelpressure.getVoltage() - 0.27)));
Thread.sleep(200);
}
#Override
public void disconnected() {
enableUi(false);
}
}
#Override
protected IOIOLooper createIOIOLooper() {
int sdoPin = 1; // DO
int sdaPin = 29; // we do not use this pin but the IOIOLib requires we specify it, so we pick an unused pin
int sclPin = 2; // CLK
int csPin = 3; // CS
SpiMaster.Rate rate = SpiMaster.Rate.RATE_31K;
final MAX31855 max31855 = new MAX31855(sdoPin, sdaPin, sclPin, csPin, rate);
max31855.setListener(new MAX31855.MAX31855Listener() {
private long faultTime;
#Override
public void onData(float internal, float thermocouple) {
updateTextView(internalText, "Internal = " + internal + " C");
updateTextView(thermocoupleText, thermocouple + " C");
float secondsSinceFault = (System.nanoTime() - faultTime) / 1000000000.0f;
if (secondsSinceFault > FAULT_DISPLAY_DURATION) {
updateTextView(faultsText, "Faults = ");
}
}
#Override
public void onFault(byte f) {
List<String> faults = new ArrayList<String>();
if ((f & MAX31855.FAULT_OPEN_CIRCUIT_BIT) == MAX31855.FAULT_OPEN_CIRCUIT_BIT)
faults.add("Open Circuit");
if ((f & MAX31855.FAULT_SHORT_TO_GND_BIT) == MAX31855.FAULT_SHORT_TO_GND_BIT)
faults.add("Short To GND");
if ((f & MAX31855.FAULT_SHORT_TO_VCC_BIT) == MAX31855.FAULT_SHORT_TO_VCC_BIT)
faults.add("Short To VCC");
boolean first = true;
String text = "Faults = ";
for (String fault : faults) {
if (!first)
text += ", ";
text += fault;
}
if (faults.size() > 0) {
faultTime = System.nanoTime();
}
updateTextView(faultsText, text);
}
});
return new IOIOSimpleApp.DeviceLooper(max31855);
}
private void enableUi(final boolean enable) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//seekBar_.setEnabled(enable);
//toggleButton_.setEnabled(enable);
}
});
}
private void setNumber1(double f) {
final String str = String.format("%.0f", f);
runOnUiThread(new Runnable() {
#Override
public void run() {
boost.setText(str);
}
});
}
private void setNumber2(double f) {
final String str = String.format("%.0f", f);
runOnUiThread(new Runnable() {
#Override
public void run() {
fuelpressure.setText(str);
}
});
}
private void updateTextView(final TextView textView, final String text) {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(text);
}
});
}
/**
* This is the thread on which all the IOIO activity happens. It will be run
* every time the application is resumed and aborted when it is paused. The
* method setup() will be called right after a connection with the IOIO has
* been established (which might happen several times!). Then, loop() will
* be called repetitively until the IOIO gets disconnected.
*/
class DeviceLooper extends BaseIOIOLooper {
private IOIOLooper device;
public DeviceLooper(IOIOLooper device) {
this.device = device;
}
#Override
public void setup() throws ConnectionLostException, InterruptedException {
device.setup(ioio_);
updateTextView(ioioStatusText, "IOIO Connected");
}
#Override
public void loop() throws ConnectionLostException, InterruptedException {
device.loop();
}
#Override
public void disconnected() {
device.disconnected();
updateTextView(ioioStatusText, "IOIO Disconnected");
}
#Override
public void incompatible() {
updateTextView(ioioStatusText, "IOIO Incompatible");
}
} }
Hope this is work :)

How to auto refresh to list messages?

I have small problem. My problem is auto refresh to list messages.
How can instantly check data such as WhatsApp ?
If you would like to automatically update data came from.
I do not know exactly how I can do , so I'm waiting for your help .
Code
MessagingActivity.java
package com.socialnetwork.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.socialnetwork.R;
import com.socialnetwork.adapters.MessagesAdapter;
import com.socialnetwork.animation.ViewAudioProxy;
import com.socialnetwork.api.APIService;
import com.socialnetwork.api.ChatAPI;
import com.socialnetwork.api.UsersAPI;
import com.socialnetwork.data.MessagesItem;
import com.socialnetwork.data.userItem;
import com.socialnetwork.helpers.M;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MessagingActivity extends AppCompatActivity implements OnClickListener {
public Intent mIntent = null;
private MediaRecorder recorder = null;
private String outFile = null;
private TextView recordTimeText;
private ImageButton audioSendButton;
private View recordPanel;
private View slideText;
private float startedDraggingX = -1;
private float distCanMove = dp(80);
private long startTime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private Timer timer;
public int RECIPIENT_ID = 0,
CONVERSATION_ID = 0;
public LinearLayoutManager layoutManager;
private EditText messageField;
private String messageBody, USERNAME;
private MessagesAdapter messageAdapter;
private List<MessagesItem> mMessages = new ArrayList<MessagesItem>();
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
Bundle data = intent.getBundleExtra("data");
if (Integer.parseInt(data.getString("ownerID")) == RECIPIENT_ID) {
MessagesItem newMsg = new MessagesItem();
newMsg.setOwnerName(data.getString("ownerName"));
newMsg.setId(Integer.parseInt(data.getString("id")));
newMsg.setMessage(data.getString("message"));
newMsg.setDate(data.getString("date"));
newMsg.setOwnerUsername(data.getString("ownerUsername"));
newMsg.setOwnerPicture(data.getString("ownerPicture"));
newMsg.setOwnerID(Integer.parseInt(data.getString("ownerID")));
newMsg.setConversationID(Integer.parseInt(data.getString("conversationID")));
addMessage(newMsg);
} else {
Intent resultIntent = new Intent(MessagingActivity.this, MessagingActivity.class);
resultIntent.putExtra("data", intent);
M.showNotification(MessagingActivity.this, resultIntent,
data.getString("ownerUsername"),
data.getString("message"),
Integer.parseInt(data.getString("conversationID")));
}
}
};
private RecyclerView messagesList;
private LinearLayout attachLayout;
private RelativeLayout recordPannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (M.getToken(this) == null) {
Intent mIntent = new Intent(this, LoginActivity.class);
startActivity(mIntent);
finish();
} else {
setContentView(R.layout.messaging);
initializer();
if (getIntent().hasExtra("conversationID")) {
CONVERSATION_ID = getIntent().getExtras().getInt("conversationID");
}
if (getIntent().hasExtra("recipientID")) {
RECIPIENT_ID = getIntent().getExtras().getInt("recipientID");
}
getUser();
getMessages();
}
}
public void initializer() {
messagesList = (RecyclerView) findViewById(R.id.listMessages);
messageAdapter = new MessagesAdapter(this, mMessages);
messagesList.setAdapter(messageAdapter);
//
layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setStackFromEnd(true);
messagesList.setLayoutManager(layoutManager);
messageField = (EditText) findViewById(R.id.messageField);
attachLayout = (LinearLayout) findViewById(R.id.attachLayout);
recordPannel = (RelativeLayout) findViewById(R.id.record_pannel);
recordPanel = findViewById(R.id.record_panel);
recordTimeText = (TextView) findViewById(R.id.recording_time_text);
slideText = findViewById(R.id.slideText);
audioSendButton = (ImageButton) findViewById(R.id.chat_audio_send_button);
TextView textView = (TextView) findViewById(R.id.slideToCancelTextView);
textView.setText("Slide To Cancel");
//including toolbar and enabling the home button
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(R.id.attachBtn).setOnClickListener(this);
findViewById(R.id.sendBtn).setOnClickListener(this);
findViewById(R.id.micBtn).setOnClickListener(this);
audioSendButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText
.getLayoutParams();
params.leftMargin = dp(30);
slideText.setLayoutParams(params);
ViewAudioProxy.setAlpha(slideText, 1);
startedDraggingX = -1;
startRecording();
audioSendButton.getParent()
.requestDisallowInterceptTouchEvent(true);
recordPanel.setVisibility(View.VISIBLE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP
|| motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
startedDraggingX = -1;
stopRecording();
recordPannel.setVisibility(View.GONE);
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
float x = motionEvent.getX();
if (x < -distCanMove) {
stopRecording();
}
x = x + ViewAudioProxy.getX(audioSendButton);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText
.getLayoutParams();
if (startedDraggingX != -1) {
float dist = (x - startedDraggingX);
params.leftMargin = dp(30) + (int) dist;
slideText.setLayoutParams(params);
float alpha = 1.0f + dist / distCanMove;
if (alpha > 1) {
alpha = 1;
} else if (alpha < 0) {
alpha = 0;
}
ViewAudioProxy.setAlpha(slideText, alpha);
}
if (x <= ViewAudioProxy.getX(slideText) + slideText.getWidth()
+ dp(30)) {
if (startedDraggingX == -1) {
startedDraggingX = x;
distCanMove = (recordPanel.getMeasuredWidth()
- slideText.getMeasuredWidth() - dp(48)) / 2.0f;
if (distCanMove <= 0) {
distCanMove = dp(80);
} else if (distCanMove > dp(80)) {
distCanMove = dp(80);
}
}
}
if (params.leftMargin > dp(30)) {
params.leftMargin = dp(30);
slideText.setLayoutParams(params);
ViewAudioProxy.setAlpha(slideText, 1);
startedDraggingX = -1;
}
}
view.onTouchEvent(motionEvent);
return true;
}
});
}
private void getUser() {
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.getUser(RECIPIENT_ID, new Callback<userItem>() {
#Override
public void success(userItem userItem, retrofit.client.Response response) {
if (userItem.getName() != null) {
getSupportActionBar().setTitle(userItem.getName());
} else {
getSupportActionBar().setTitle(userItem.getUsername());
}
}
#Override
public void failure(RetrofitError error) {
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
messageAdapter.stop();
}
public void getMessages() {
M.showLoadingDialog(this);
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(this));
mChatAPI.getMessages(CONVERSATION_ID, RECIPIENT_ID, 1, new Callback<List<MessagesItem>>() {
#Override
public void success(List<MessagesItem> messagesItems, Response response) {
mMessages = messagesItems;
messageAdapter.setMessages(messagesItems);
M.hideLoadingDialog();
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
M.L(getString(R.string.ServerError));
}
});
}
private void sendMessage() {
messageBody = messageField.getText().toString().trim();
if (!messageBody.isEmpty()) {
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(this));
mChatAPI.addMessage(messageBody, CONVERSATION_ID, RECIPIENT_ID, new Callback<MessagesItem>() {
#Override
public void success(MessagesItem messagesItem, Response response) {
if (messagesItem != null) {
mMessages.add(messagesItem);
messageAdapter.setMessages(mMessages);
messagesList.smoothScrollToPosition(mMessages.size());
messageField.setText("");
} else {
M.T(MessagingActivity.this, getString(R.string.SomethingWentWrong));
}
}
#Override
public void failure(RetrofitError error) {
M.T(MessagingActivity.this, getString(R.string.ServerError));
}
});
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.attachBtn) {
if (attachLayout.getVisibility() == View.GONE) {
attachLayout.setVisibility(View.VISIBLE);
} else {
attachLayout.setVisibility(View.GONE);
}
if (recordPannel.getVisibility() == View.VISIBLE) {
recordPannel.setVisibility(View.GONE);
}
} else if (v.getId() == R.id.sendBtn) {
sendMessage();
} else if (v.getId() == R.id.micBtn) {
attachLayout.setVisibility(View.GONE);
recordPannel.setVisibility(View.VISIBLE);
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mMessageReceiver, new IntentFilter("update_messages_list"));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mMessageReceiver);
}
public void addMessage(MessagesItem newMsg) {
mMessages.add(newMsg);
messageAdapter.setMessages(mMessages);
messagesList.smoothScrollToPosition(mMessages.size());
}
private void startRecording() {
try {
startRecordingAudio();
} catch (IOException e) {
e.printStackTrace();
}
startTime = SystemClock.uptimeMillis();
timer = new Timer();
MyTimerTask myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 1000, 1000);
vibrate();
}
private void stopRecording() {
if (timer != null) {
timer.cancel();
}
if (recordTimeText.getText().toString().equals("00:00")) {
return;
}
recordTimeText.setText("00:00");
vibrate();
Toast.makeText(getApplicationContext(), "Stop Recording", Toast.LENGTH_SHORT).show();
stopRecordingAudio();
}
public void startRecordingAudio() throws IOException {
Toast.makeText(getApplicationContext(), "Start Recording...", Toast.LENGTH_SHORT).show();
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH.mm.ss");
String fileName = "audio_" + timeStampFormat.format(new Date())
+ ".mp3";
outFile = "/sdcard/";// Environment.getExternalStorageDirectory().getAbsolutePath();
stopRecordingAudio();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outFile + fileName);
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
recorder.prepare();
recorder.start();
}
public void stopRecordingAudio() {
if (recorder != null) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(MessagingActivity.this, "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(MessagingActivity.this, "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
}
};
private void vibrate() {
// TODO Auto-generated method stub
try {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(200);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int dp(float value) {
return (int) Math.ceil(1 * value);
}
class MyTimerTask extends TimerTask {
#Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
final String hms = String.format(
"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(updatedTime)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(updatedTime)),
TimeUnit.MILLISECONDS.toSeconds(updatedTime)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(updatedTime)));
long lastsec = TimeUnit.MILLISECONDS.toSeconds(updatedTime)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(updatedTime));
System.out.println(lastsec + " hms " + hms);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if (recordTimeText != null)
recordTimeText.setText(hms);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
}
}
MessagesFragment.java
public class MessagesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public RecyclerView conversationList;
public ConversationsAdapter mConversationsAdapter;
public List<ConversationItem> mConversations = new ArrayList<ConversationItem>();
public Intent mIntent = null;
public int currentPage = 1;
public LinearLayoutManager layoutManager;
private View mView;
private SwipeRefreshLayout mSwipeRefreshLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_messages, container, false);
conversationList = (RecyclerView) mView
.findViewById(R.id.conversationsList);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.title_messages);
initializeView();
conversationList.setOnScrollListener(new HidingScrollListener(layoutManager) {
#Override
public void onHide() {
}
#Override
public void onShow() {
}
#Override
public void onLoadMore(int currentPage) {
setCurrentPage(currentPage);
getConversations();
}
});
mSwipeRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.swipeMessages);
mSwipeRefreshLayout.setOnRefreshListener(this);
getConversations();
return mView;
}
public void initializeView() {
mConversationsAdapter = new ConversationsAdapter(getActivity(),
mConversations);
conversationList.setAdapter(mConversationsAdapter);
layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
conversationList.setLayoutManager(layoutManager);
}
public void getConversations() {
M.showLoadingDialog(getActivity());
ChatAPI mChatAPI = APIService.createService(ChatAPI.class, M.getToken(getActivity()));
mChatAPI.getConversations(getCurrentPage(), new Callback<List<ConversationItem>>() {
#Override
public void success(List<ConversationItem> conversationItems, retrofit.client.Response response) {
M.L(response.getBody().mimeType());
mConversationsAdapter.setConversations(conversationItems);
M.hideLoadingDialog();
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
}
});
}
#Override
public void onRefresh() {
setCurrentPage(1);
getConversations();
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
WhatsApp is not instant check. It's is more like:
Screen off, check 10x after 30s, next 10x after 1m, next 3x after 5m and so on. and start again if the screen turns off again. WhatsApp is checkin in the background also when you close the app. They are using a service.

Set onclickLister in utube api

i'm using youtubeApi (https://developers.google.com/youtube/android/player/downloads/), I'm looking for a solution for put an onclick listener on the videos on the VideoWall..
package com.android.youbho.Activities;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.PlayerStyle;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.android.youbho.Utils.Constant;
import com.android.youbho.Utils.FlippingView;
import com.android.youbho.Utils.ImageWallView;
#SuppressLint("NewApi") public class VideoWallActivity extends Activity implements
FlippingView.Listener,
YouTubePlayer.OnInitializedListener,
YouTubeThumbnailView.OnInitializedListener{
private static final int RECOVERY_DIALOG_REQUEST = 1;
/** The player view cannot be smaller than 110 pixels high. */
private static final float PLAYER_VIEW_MINIMUM_HEIGHT_DP = 110;
private static final int MAX_NUMBER_OF_ROWS_WANTED = 4;
// Example playlist from which videos are displayed on the video wall
private static final String PLAYLIST_ID = "PLBA95EAD360E2B0D1";
private static final int INTER_IMAGE_PADDING_DP = 5;
// YouTube thumbnails have a 16 / 9 aspect ratio
private static final double THUMBNAIL_ASPECT_RATIO = 16 / 9d;
private static final int INITIAL_FLIP_DURATION_MILLIS = 100;
private static final int FLIP_DURATION_MILLIS = 500;
private static final int FLIP_PERIOD_MILLIS = 2000;
private ImageWallView imageWallView;
private Handler flipDelayHandler;
private FlippingView flippingView;
private YouTubeThumbnailView thumbnailView;
private YouTubeThumbnailLoader thumbnailLoader;
private YouTubePlayerFragment playerFragment;
private View playerView;
private YouTubePlayer player;
private Dialog errorDialog;
private int flippingCol;
private int flippingRow;
private int videoCol;
private int videoRow;
private boolean nextThumbnailLoaded;
private boolean activityResumed;
private State state;
private static final int id_videoPlayer=99;
private enum State {
UNINITIALIZED,
LOADING_THUMBNAILS,
VIDEO_FLIPPED_OUT,
VIDEO_LOADING,
VIDEO_CUED,
VIDEO_PLAYING,
VIDEO_ENDED,
VIDEO_BEING_FLIPPED_OUT,
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Toast.makeText(getApplicationContext(), "lol:" + position, Toast.LENGTH_LONG).show();
return view;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #SuppressLint("NewApi") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
state = State.UNINITIALIZED;
ViewGroup viewFrame = new FrameLayout(this);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int maxAllowedNumberOfRows = (int) Math.floor((displayMetrics.heightPixels / displayMetrics.density) / PLAYER_VIEW_MINIMUM_HEIGHT_DP);
int numberOfRows = Math.min(maxAllowedNumberOfRows, MAX_NUMBER_OF_ROWS_WANTED);
int interImagePaddingPx = (int) displayMetrics.density * INTER_IMAGE_PADDING_DP;
int imageHeight = (displayMetrics.heightPixels / numberOfRows) - interImagePaddingPx;
int imageWidth = (int) (imageHeight * THUMBNAIL_ASPECT_RATIO);
imageWallView = new ImageWallView(this, imageWidth, imageHeight, interImagePaddingPx);
viewFrame.addView(imageWallView, MATCH_PARENT, MATCH_PARENT);
thumbnailView = new YouTubeThumbnailView(this);
thumbnailView.initialize(Constant.DEVELOPER_KEY, this);
flippingView = new FlippingView(this, this, imageWidth, imageHeight);
flippingView.setFlipDuration(INITIAL_FLIP_DURATION_MILLIS);
viewFrame.addView(flippingView, imageWidth, imageHeight);
playerView = new FrameLayout(this);
playerView.setId(id_videoPlayer);
playerView.setVisibility(View.INVISIBLE);
viewFrame.addView(playerView, imageWidth, imageHeight);
playerFragment = YouTubePlayerFragment.newInstance();
playerFragment.initialize(Constant.DEVELOPER_KEY, this);
getFragmentManager().beginTransaction().add(id_videoPlayer, playerFragment).commit();
flipDelayHandler = new FlipDelayHandler();
setContentView(viewFrame);
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView, YouTubeThumbnailLoader thumbnailLoader) {
thumbnailView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "lol! ", Toast.LENGTH_LONG).show();
}
});
this.thumbnailLoader = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailListener());
maybeStartDemo();
}
#Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
if (errorDialog == null || !errorDialog.isShowing()) {
errorDialog = errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST);
errorDialog.show();
}
} else {
String errorMessage = String.format( errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasResumed) {
VideoWallActivity.this.player = player;
player.setPlayerStyle(PlayerStyle.CHROMELESS);
player.setPlayerStateChangeListener(new VideoListener());
maybeStartDemo();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
if (errorDialog == null || !errorDialog.isShowing()) {
errorDialog = errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST);
errorDialog.show();
}
} else {
String errorMessage = String.format( errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
private void maybeStartDemo() {
if (activityResumed && player != null && thumbnailLoader != null && state.equals(State.UNINITIALIZED)) {
thumbnailLoader.setPlaylist(PLAYLIST_ID); // loading the first thumbnail will kick off demo
state = State.LOADING_THUMBNAILS;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
if (errorDialog != null && errorDialog.isShowing()) {
errorDialog.dismiss();
}
errorDialog = null;
playerFragment.initialize(Constant.DEVELOPER_KEY, this);
thumbnailView.initialize(Constant.DEVELOPER_KEY, this);
}
}
#Override
protected void onResume() {
super.onResume();
activityResumed = true;
if (thumbnailLoader != null && player != null) {
if (state.equals(State.UNINITIALIZED)) {
maybeStartDemo();
} else if (state.equals(State.LOADING_THUMBNAILS)) {
loadNextThumbnail();
} else {
if (state.equals(State.VIDEO_PLAYING)) {
player.play();
}
flipDelayHandler.sendEmptyMessageDelayed(0, FLIP_DURATION_MILLIS);
}
}
}
#Override
protected void onPause() {
flipDelayHandler.removeCallbacksAndMessages(null);
activityResumed = false;
super.onPause();
}
#Override
protected void onDestroy() {
if (thumbnailLoader != null) {
thumbnailLoader.release();
}
super.onDestroy();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) private void flipNext() {
if (!nextThumbnailLoaded || state.equals(State.VIDEO_LOADING)) {
return;
}
if (state.equals(State.VIDEO_ENDED)) {
flippingCol = videoCol;
flippingRow = videoRow;
state = State.VIDEO_BEING_FLIPPED_OUT;
} else {
Pair<Integer, Integer> nextTarget = imageWallView.getNextLoadTarget();
flippingCol = nextTarget.first;
flippingRow = nextTarget.second;
}
flippingView.setX(imageWallView.getXPosition(flippingCol, flippingRow));
flippingView.setY(imageWallView.getYPosition(flippingCol, flippingRow));
flippingView.setFlipInDrawable(thumbnailView.getDrawable());
flippingView.setFlipOutDrawable(imageWallView.getImageDrawable(flippingCol, flippingRow));
imageWallView.setImageDrawable(flippingCol, flippingRow, thumbnailView.getDrawable());
imageWallView.hideImage(flippingCol, flippingRow);
flippingView.setVisibility(View.VISIBLE);
flippingView.flip();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onFlipped(FlippingView view) {
imageWallView.showImage(flippingCol, flippingRow);
flippingView.setVisibility(View.INVISIBLE);
if (activityResumed) {
loadNextThumbnail();
if (state.equals(State.VIDEO_BEING_FLIPPED_OUT)) {
state = State.VIDEO_FLIPPED_OUT;
} else if (state.equals(State.VIDEO_CUED)) {
videoCol = flippingCol;
videoRow = flippingRow;
playerView.setX(imageWallView.getXPosition(flippingCol, flippingRow));
playerView.setY(imageWallView.getYPosition(flippingCol, flippingRow));
imageWallView.hideImage(flippingCol, flippingRow);
playerView.setVisibility(View.VISIBLE);
player.play();
state = State.VIDEO_PLAYING;
} else if (state.equals(State.LOADING_THUMBNAILS) && imageWallView.allImagesLoaded()) {
state = State.VIDEO_FLIPPED_OUT; // trigger flip in of an initial video
flippingView.setFlipDuration(FLIP_DURATION_MILLIS);
flipDelayHandler.sendEmptyMessage(0);
}
}
}
private void loadNextThumbnail() {
nextThumbnailLoaded = false;
if (thumbnailLoader.hasNext()) {
thumbnailLoader.next();
} else {
thumbnailLoader.first();
}
}
/**
* A handler that periodically flips an element on the video wall.
*/
#SuppressLint("HandlerLeak")
private final class FlipDelayHandler extends Handler {
#Override
public void handleMessage(Message msg) {
flipNext();
sendEmptyMessageDelayed(0, FLIP_PERIOD_MILLIS);
}
}
/**
* An internal listener which listens to thumbnail loading events from the
* {#link YouTubeThumbnailView}.
*/
private final class ThumbnailListener implements YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView thumbnail, String videoId) {
nextThumbnailLoaded = true;
if (activityResumed) {
if (state.equals(State.LOADING_THUMBNAILS)) {
flipNext();
} else if (state.equals(State.VIDEO_FLIPPED_OUT)) {
// load player with the video of the next thumbnail being flipped in
state = State.VIDEO_LOADING;
player.cueVideo(videoId);
}
}
}
#Override
public void onThumbnailError(YouTubeThumbnailView thumbnail, YouTubeThumbnailLoader.ErrorReason reason) {
loadNextThumbnail();
}
}
private final class VideoListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onLoaded(String videoId) {
state = State.VIDEO_CUED;
}
#Override
public void onVideoEnded() {
state = State.VIDEO_ENDED;
imageWallView.showImage(videoCol, videoRow);
playerView.setVisibility(View.INVISIBLE);
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
if (errorReason == YouTubePlayer.ErrorReason.UNEXPECTED_SERVICE_DISCONNECTION) {
// player has encountered an unrecoverable error - stop the demo
flipDelayHandler.removeCallbacksAndMessages(null);
state = State.UNINITIALIZED;
thumbnailLoader.release();
thumbnailLoader = null;
player = null;
} else {
state = State.VIDEO_ENDED;
}
}
// ignored callbacks
#Override
public void onVideoStarted() { }
#Override
public void onAdStarted() { }
#Override
public void onLoading() { }
}
}
In this way, there are a list of videos in the playlist, each video will start automatically when the first is finished. I need to click each video in the wall for start it
You can add an onClickListener to the ImageViews in the ImageWallView.java class, something like this:
for (int col = 0; col < numberOfColumns; col++) {
for (int row = 0; row < numberOfRows; row++) {
int elementIdx = getElementIdx(col, row);
if (images[elementIdx] == null) {
ImageView thumbnail = new ImageView(context);
thumbnail.setLayoutParams(new LayoutParams(imageWidth, imageHeight));
images[elementIdx] = thumbnail;
unInitializedImages.add(elementIdx);
thumbnail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageWallView.this.context.startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(
ImageWallView.this.context, (String)v.getTag(), true, false));
}
});
}
addView(images[elementIdx]);
}
}
Then you will need to add the video id as the tag in YouTubeThumbnailView in VideoWallActivity.java
Hope that helps
You can use ImageView OnClickListener as suggested in previous answer: (onSizeChanged in ImageWallView.java)
for (int col = 0; col < numberOfColumns; col++) {
for (int row = 0; row < numberOfRows; row++) {
int elementIdx = getElementIdx(col, row);
if (images[elementIdx] == null) {
ImageView thumbnail = new ImageView(context);
thumbnail.setLayoutParams(new LayoutParams(imageWidth, imageHeight));
images[elementIdx] = thumbnail;
unInitializedImages.add(elementIdx);
thumbnail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageWallView.this.context.startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(
ImageWallView.this.context, (String)v.getTag(), true, false));
}
});
}
addView(images[elementIdx]);
}
}
Then you need to store video id to the calling view of ImageWallView . (set and get tag is also used to store objects between views).
To get the child view of ImageWallView, use imageWallView.getChildAt(index). index is the position of ImageView which is clicked on ImageWallView. to get this index, use getElementIdx(col,row). You need to make this method public in ImageWallView.java.
EDITED
To use the Video ID of current thumbnail, Store the VideoID in onFlipped event. This is because onThumbnailLoaded the VideoID of next thumbnail available which immediately get Flipped and available on IamgeWallView. As VideoID is not available in onFlipped event, use it from onThumbnailLoaded event
Here it is:
Declare below string in class
private String strThumbnailVideoId;
set VideoID in onThumbnailLoaded event (in VideoWallActivity.java) into strThumbnailVideoId. This video ID will be of next thumbnail which will be flipped.
#Override
public void onThumbnailLoaded(YouTubeThumbnailView thumbnail, String videoId) {
nextThumbnailLoaded = true;
strThumbnailVideoId = videoId;
if (activityResumed) {
if (state.equals(State.LOADING_THUMBNAILS)) {
flipNext();
} else if (state.equals(State.VIDEO_FLIPPED_OUT)) {
// load player with the video of the next thumbnail being flipped in
state = State.VIDEO_LOADING;
player.cueVideo(videoId);
}
}
}
Now set the strThumbnailVideoId in onFlipped as a ImageWallView tag.
#Override
public void onFlipped(FlippingView view) {
imageWallView.showImage(flippingCol, flippingRow);
flippingView.setVisibility(View.INVISIBLE);
imageWallView.getChildAt(imageWallView.getElementIdx(flippingCol, flippingRow)).setTag(strThumbnailVideoId);
......
......

Categories