Kotlin version of Illumination
Why Sony don't show how to use their cool apis...
If other apps not use some cool Sony's apis its useless to put hardware
Only Sony Music and Album app uses LED ILLUMINATION
putting HW only for two app is useless
Sony has really cool features in their HW.
Sony should show how to use their cool apis to get full outcome from Xperia.
There is lots of cool things inside Xperia. Just need to come out to their clients.
PHP:
import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.AsyncTask
object IlluminationUtil {
private val RGB_LED_ON_TIME = 4000
private val MUSIC_BEAT_LED_ON_TIME = 600000
private val ILLUMINATION_SERVICE_COMPONENT = ComponentName("com.sonyericsson.illumination.service", "com.sonyericsson.illumination.service.IlluminationService")
class getIllumination(private val context: Context, private val rgb: Int, private val enableBeat: Boolean?) : AsyncTask<Long, Void, Any>() {
protected override fun doInBackground(vararg longs: Long?): Any? {
try {
if (rgb <= 0) {
if (enableBeat!!) {
startMusicBeatIllumination(context, rgb)
} else {
//stopMusicBeatIllumination(context)
//startRGBIllumination(context, rgb)
startMusicBeatIllumination(context, rgb)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
}
class stopIllumination(private val context: Context) : AsyncTask<Long, Void, Any>() {
override fun doInBackground(vararg p0: Long?) {
try {
stopMusicBeatIllumination(context)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
@Throws(Exception::class)
fun startRGBIllumination(context: Context, rgb: Int) {
val intent = createIlluminationServiceIntent("com.sonyericsson.illumination.intent.action.START_LED")
intent.putExtra("com.sonyericsson.illumination.intent.extra.LED_ID", "com.sonyericsson.illumination.intent.extra.value.BUTTON_RGB")
intent.putExtra("com.sonyericsson.illumination.intent.extra.PACKAGE_NAME", context.packageName)
intent.putExtra("com.sonyericsson.illumination.intent.extra.LED_COLOR", rgb)
intent.putExtra("com.sonyericsson.illumination.intent.extra.LED_ON_TIME", RGB_LED_ON_TIME)
context.startService(intent)
}
@Throws(Exception::class)
private fun stopRGBIllumination(context: Context) {
val intent = createIlluminationServiceIntent("com.sonyericsson.illumination.intent.action.STOP_LED")
intent.putExtra("com.sonyericsson.illumination.intent.extra.LED_ID", "com.sonyericsson.illumination.intent.extra.value.BUTTON_RGB")
intent.putExtra("com.sonyericsson.illumination.intent.extra.PACKAGE_NAME", context.packageName)
context.startService(intent)
}
@Throws(Exception::class)
fun startMusicBeatIllumination(context: Context, color: Int) {
startRGBIllumination(context, color)
val intent = createIlluminationServiceIntent("com.sonyericsson.illumination.intent.action.START_LED")
intent.putExtra("com.sonyericsson.illumination.intent.extra.LED_ID", "com.sonyericsson.illumination.intent.extra.value.AUDIO")
intent.putExtra("com.sonyericsson.illumination.intent.extra.PACKAGE_NAME", context.packageName)
intent.putExtra("com.sonyericsson.illumination.intent.extra.LED_COLOR", color)
intent.putExtra("com.sonyericsson.illumination.intent.extra.LED_ON_TIME", MUSIC_BEAT_LED_ON_TIME)
context.startService(intent)
}
@Throws(Exception::class)
fun stopMusicBeatIllumination(context: Context) {
stopRGBIllumination(context)
val intent = createIlluminationServiceIntent("com.sonyericsson.illumination.intent.action.STOP_LED")
intent.putExtra("com.sonyericsson.illumination.intent.extra.LED_ID", "com.sonyericsson.illumination.intent.extra.value.AUDIO")
intent.putExtra("com.sonyericsson.illumination.intent.extra.PACKAGE_NAME", context.packageName)
context.startService(intent)
}
@SuppressLint("WrongConstant")
private fun isIlluminationServiceAvailable(context: Context): Boolean {
val intent = createIlluminationServiceIntent("com.sonyericsson.illumination.intent.action.START_LED")
intent.putExtra("com.sonyericsson.illumination.intent.extra.PACKAGE_NAME", context.packageName)
return if (context.packageManager.resolveService(intent, 64) != null) {
true
} else false
}
private fun createIlluminationServiceIntent(intentAction: String): Intent {
val intent = Intent()
intent.component = ILLUMINATION_SERVICE_COMPONENT
intent.action = intentAction
return intent
}
}
would be good if you would give more details, how to use it, wich models does it support and how it looks
Xperia M2 and M got that LED
Related
Hi,
I am trying to write simple cache class. Class uses SoftReference in order to avoid killing application.
Code:
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
public class MemoryCache {
// singleton implemtation
private static MemoryCache instance = null;
protected MemoryCache() { }
public static MemoryCache getInstance() {
if(instance == null) {
instance = new MemoryCache();
}
return instance;
}
//
private Map<String, SoftReference<Object>> cachedItems = new HashMap<String, SoftReference<Object>>();
public void saveCacheItem(String itemId, Object objForCache) {
cachedItems.put(itemId, new SoftReference<Object>(objForCache));
}
public Object getCacheItem(String itemId) {
if(cacheItemExists(itemId)) {
return cachedItems.get(itemId).get();
}
else {
return null;
}
}
public Boolean cacheItemExists(String itemId) {
if(cachedItems.containsKey(itemId)) {
if(cachedItems.get(itemId) != null ) {
return true;
}
}
return false;
}
public void deleteCacheItem(String itemId) {
if(cachedItems.containsKey(itemId)) {
cachedItems.remove(itemId);
}
}
}
However, referenced objects are cleaned too early. Even though cached item is a class with just few attributes, its lifespan is very short.
I tested this functionality only on android emulator.
Does my class cause problem or garbage collector/vm?
I am currently working on an App Switcher with the ability to also add custom apps in the app switcher. So, I already got the recent apps loader built. This is the code for this part of the app:
Code:
public class Corners_RecentApps extends Activity {
private ArrayList<PanelItemDetail> rowItems = null;
private ListView listView;
private ArrayList<String> packageName = null;
private ArrayList<String> className = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
if(rightpanel){
overridePendingTransition(R.anim.left_slide_in_fast, 0);
setContentView(R.layout.right_side_panel);
}
else
{
overridePendingTransition(R.anim.right_slide_in_fast, 0);
setContentView(R.layout.activity_left_side_panel);
}
ImageView imgbtn = (ImageView) findViewById(R.id.transparentbackground);
ImageView panelbg = (ImageView) findViewById(R.id.panelbackground);
listView = (ListView)findViewById(R.id.panelcontents);
packageName = new ArrayList<String>();
className = new ArrayList<String>();
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = am.getRecentTasks(30, 0);
rowItems = new ArrayList<PanelItemDetail>();
PackageManager pacMgr = getPackageManager();
for (ActivityManager.RecentTaskInfo recentTask : tasks) {
try {
rowItems.add(new PanelItemDetail(pacMgr.getApplicationIcon(recentTask.origActivity.getPackageName())));
packageName.add(recentTask.origActivity.getPackageName());
className.add(recentTask.origActivity.getClassName());
Log.d("#@#", "getPackageName = " + recentTask.origActivity.getPackageName());
Log.d("#@#", "getClassName = " + recentTask.origActivity.getClassName());
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
String itembg = myPreference.getString("itembg_list", "");
if(itembg.equals("defaults"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_default, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("dark"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_dark, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("light"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_light, rowItems);
listView.setAdapter(adapter);
}
else
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_none, rowItems);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
try{
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
Intent taskintent = getPackageManager().getLaunchIntentForPackage(packageName.get(postion).toString());
startActivity(taskintent);
if(rightpanel){
overridePendingTransition(R.anim.right_slide_in, R.anim.zoom_out);
}
else
{
overridePendingTransition(R.anim.left_slide_in, R.anim.zoom_out);
}
finish();
}
catch (NullPointerException fail) {
Toast.makeText(getApplicationContext(), "!", Toast.LENGTH_SHORT).show();
}
}
});
SharedPreferences panelbgpref = PreferenceManager.getDefaultSharedPreferences(this);
String panelbgset = panelbgpref.getString("panelbg_list", "");
if(panelbgset.equals("light"))
{
panelbg.setImageResource(R.drawable.panelbg_light);
}
else
{
panelbg.setImageResource(R.drawable.panelbg);
}
imgbtn.setOnClickListener(new View.OnClickListener(){
[user=439709]@override[/user]
public void onClick(View v) {
if(v.getId() ==R.id.transparentbackground){
moveTaskToBack(true);
finish();
}
}
});
}
Now I want to let the users define in the app settings up to 3 own apps that should be shown on every moment.
How should I do that?
Thank you
For my App I want when you click into the autocompletetextview it will bring up a list of chemicals and then when you choose your chemical it will put the chemical name in the autocomplete field and also put the corresponding weight into an edittext field.
The approach I went with this was using a customadapter so when you pick one it will give the other. It is my first time making one so I'm not sure if it's 100% correct. It would be great if you guys had any suggestions. Thanks
Currently this is the code that I have.
editText4 is the autocompletetextview field I want the chemical name to appear in.
editText is the editText field i want the number to appear in.
MainActivity .java
Code:
public void Chem() {
Chemical chemical_data[] = new Chemical[]
{
new Chemical("Acid", 125.33),
new Chemical("Blue", 145.3356),
};
ChemicalAdapter adapter = new ChemicalAdapter(this, R.layout.sollayout, chemical_data);
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
weightval = (EditText) findViewById(R.id.editText);
//ChemicalAdapter header = new ChemicalAdapter(this, R.layout.sollayout, null);
//weightval.addHeaderView(header);
chemname.setAdapter(adapter);
}
public void Chemname()
{
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
AutoCompleteTextView b = (AutoCompleteTextView) findViewById(R.id.editText4);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Chem();
}
});
}
Chemical.java
Code:
public class Chemical {
String chemicalValue;
double weight;
public Chemical(String chemicalValue, double weight) {
this.chemicalValue = chemicalValue;
this.weight = weight;
}
public String getChemicalValue() {
return chemicalValue;
}
public double getWeight() {
return weight;
}
}
ChemicalAdapter.java
Code:
public class ChemicalAdapter extends ArrayAdapter<Chemical> {
Context context;
int layoutResourceId;
Chemical data[] = null;
public ChemicalAdapter(Context context, int layoutResourceId, Chemical[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChemicalHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChemicalHolder();
holder.chemname = (AutoCompleteTextView)row.findViewById(R.id.editText4);
holder.weightval = (EditText)row.findViewById(R.id.editText);
row.setTag(holder);
}
else
{
holder = (ChemicalHolder)row.getTag();
}
Chemical chemical = data[position];
holder.weightval.setText(String.valueOf(chemical.weight));
holder.chemname.setText(chemical.chemicalValue);
return row;
}
static class ChemicalHolder
{
AutoCompleteTextView chemname;
EditText weightval;
}
}
As what was stated on the header I want to implement either a "paint" function for user to edit paint/censor unwanted parts of a photo displayed on a imageview before uploading it to a server in the edited format and a redo function if user makes a mistake while editing?
How do I come about doing it, I've read relevant topics on Canvas, or FingerPaint but still puzzled on how to implement it based on my project here? Tried referencing to the links here and here but without success in implementing the codes into my project code due to my lack of programming skills.
Thanks for any help rendered!
Tried integrating the codes below into my code above (image preview after taking a photo with the camera) for user to start editing via painting but still not working? Thanks for any help rendered!
Code:
public class Drawing extends View {
private Paint mPaint, mBitmapPaint;
Intent intent = getIntent();
Bitmap mBitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
private Canvas mCanvas;
private Path mPath;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private int color, size, state;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Integer> colors = new ArrayList<Integer>();
private ArrayList<Integer> sizes = new ArrayList<Integer>();
public Drawing(Context c) {
super(c);
}
public Drawing(Context c,int width, int height, int size, int color, int state) {
super(c);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
// mBitmapPaint = new Paint(Paint.DITHER_FLAG);
// mBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
setColor(color);
setSize(size);
setState(state);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
// canvas.drawColor(Color.TRANSPARENT);
// canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
//
// if (state == 0)
// mBitmap.eraseColor(Color.TRANSPARENT);
for (int i = 0; i < paths.size(); i++) {
mPaint.setColor(colors.get(i));
mPaint.setStrokeWidth(sizes.get(i));
canvas.drawPath(paths.get(i), mPaint);
}
mPaint.setColor(color);
mPaint.setStrokeWidth(size);
canvas.drawPath(mPath, mPaint);
}
public void setColor(int color) {
this.color = color;
}
public void setSize(int size) {
this.size = size;
}
public void setState(int state) {
this.state = state;
// if (state == 0)
// mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
// else
// mPaint.setXfermode(null);
}
public void onClickUndo() {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
sizes.remove(sizes.size() - 1);
colors.remove(colors.size() - 1);
invalidate();
}
}
private void touch_start(float x, float y) {
undonePaths.clear();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
colors.add(color);
sizes.add(size);
paths.add(mPath);
mPath = new Path();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
Hello,
I create that thread to present you a tutorial aiming to learn you how to create a Running Man Game Animation on Android. You can discover the tutorial in video on Youtube :
Create a Running Man Game Animation on Android
Making a Running Man Animation on Android is a great way to learn how to work with Bitmaps, Thread and SurfaceView. First thing to make a Running Man Game Animation is to have a character to animate. For that, we will use the following sprite sheet :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Like you can see, our character sprite sheet has 8 frames. Each frame show the character in a different position when he runs.
For our animation, we are going to create a custom GameView extending the SurfaceView class and implementing the Runnable interface. First, we need to define some properties like the game thread, the surface holder, the canvas where running man will be drawn, the bitmap used to load the sprite sheet and some parameters to customize the running man animation like the speed, the size or the position of the man on the screen :
Code:
class GameView extends SurfaceView implements Runnable {
private Thread gameThread;
private SurfaceHolder ourHolder;
private volatile boolean playing;
private Canvas canvas;
private Bitmap bitmapRunningMan;
private boolean isMoving;
private float runSpeedPerSecond = 500;
private float manXPos = 10, manYPos = 10;
private int frameWidth = 230, frameHeight = 274;
private int frameCount = 8;
private int currentFrame = 0;
private long fps;
private long timeThisFrame;
private long lastFrameChangeTime = 0;
private int frameLengthInMillisecond = 50;
// ...
}
To draw correctly the good frame for the running man, we need two Rectangle instances. One used to define the current frame in the sprite sheet and an other to define where to draw the current frame on the screen :
Code:
private Rect frameToDraw = new Rect(0, 0, frameWidth, frameHeight);
private RectF whereToDraw = new RectF(manXPos, manYPos,
manXPos + frameWidth, frameHeight);
On the GameView constructor, we get the surface holder and then, we load the sprite sheet into the bitmapRunningMan variable. We apply a scale transformation according values defined in frameWidth and frameHeight parameters :
Code:
public GameView(Context context) {
super(context);
ourHolder = getHolder();
bitmapRunningMan = BitmapFactory.decodeResource(getResources(),
R.drawable.running_man);
bitmapRunningMan = Bitmap.createScaledBitmap(bitmapRunningMan,
frameWidth * frameCount, frameHeight, false);
}
Now, it's time to make the event loop for animation inside the run method overrided from Runnable interface :
Code:
@Override
public void run() {
while (playing) {
long startFrameTime = System.currentTimeMillis();
update();
draw();
timeThisFrame = System.currentTimeMillis() - startFrameTime;
if (timeThisFrame >= 1) {
fps = 1000 / timeThisFrame;
}
}
}
Note that we animate the character while the playing variable is set to true. Like usual in a game, we update the elements and then we draw before to calculate frame per seconds. The update method is just used here to move the man positions in X and Y. Note that when the man reach the end of the screen horizontally or vertically, we set its position to the left or top of the screen :
Code:
public void update() {
if (isMoving) {
manXPos = manXPos + runSpeedPerSecond / fps;
if (manXPos > getWidth()) {
manYPos += (int) frameHeight;
manXPos = 10;
}
if (manYPos + frameHeight > getHeight()) {
manYPos = 10;
}
}
}
Before to write the draw method, we need to define a method to manage the current frame to display for the character. We change the current frame only when he have ended the frame duration :
Code:
public void manageCurrentFrame() {
long time = System.currentTimeMillis();
if (isMoving) {
if (time > lastFrameChangeTime + frameLengthInMillisecond) {
lastFrameChangeTime = time;
currentFrame++;
if (currentFrame >= frameCount) {
currentFrame = 0;
}
}
}
frameToDraw.left = currentFrame * frameWidth;
frameToDraw.right = frameToDraw.left + frameWidth;
}
And now, we define the draw method :
Code:
public void draw() {
if (ourHolder.getSurface().isValid()) {
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
whereToDraw.set((int) manXPos, (int) manYPos, (int) manXPos
+ frameWidth, (int) manYPos + frameHeight);
manageCurrentFrame();
canvas.drawBitmap(bitmapRunningMan, frameToDraw, whereToDraw, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
First, we check if the surface is valid. Then we lock the canvas and we draw the character current frame. Last, we unlock the canvas and post it on the Surface View. Finally, we define two methods to pause or resume the running man animation :
Code:
public void pause() {
playing = false;
try {
gameThread.join();
} catch(InterruptedException e) {
Log.e("ERR", "Joining Thread");
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
To start the running man animation, we're going to wait the user click on the surface view. So, we need to override the onTouchEvent method and wait for an ACTION_DOWN event. When the event is made, we have just to change the isMoving boolean value. If man is running, we stop it. If man doesn't run, we start to move it :
Code:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN :
isMoving = !isMoving;
break;
}
return true;
}
Last thing to make is to assemble all the pieces of the puzzle, create the game view on the main activity, set it as the content view and then resume or pause the game animation when the activity is resumed or paused :
Code:
package com.ssaurel.runningman;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class RunningManAnimation extends AppCompatActivity {
private GameView gameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new GameView(this);
setContentView(gameView);
}
@Override
protected void onResume() {
super.onResume();
gameView.resume();
}
@Override
protected void onPause() {
super.onPause();
gameView.pause();
}
class GameView extends SurfaceView implements Runnable {
private Thread gameThread;
private SurfaceHolder ourHolder;
private volatile boolean playing;
private Canvas canvas;
private Bitmap bitmapRunningMan;
private boolean isMoving;
private float runSpeedPerSecond = 500;
private float manXPos = 10, manYPos = 10;
private int frameWidth = 230, frameHeight = 274;
private int frameCount = 8;
private int currentFrame = 0;
private long fps;
private long timeThisFrame;
private long lastFrameChangeTime = 0;
private int frameLengthInMillisecond = 50;
private Rect frameToDraw = new Rect(0, 0, frameWidth, frameHeight);
private RectF whereToDraw = new RectF(manXPos, manYPos, manXPos + frameWidth, frameHeight);
public GameView(Context context) {
super(context);
ourHolder = getHolder();
bitmapRunningMan = BitmapFactory.decodeResource(getResources(), R.drawable.running_man);
bitmapRunningMan = Bitmap.createScaledBitmap(bitmapRunningMan, frameWidth * frameCount, frameHeight, false);
}
@Override
public void run() {
while (playing) {
long startFrameTime = System.currentTimeMillis();
update();
draw();
timeThisFrame = System.currentTimeMillis() - startFrameTime;
if (timeThisFrame >= 1) {
fps = 1000 / timeThisFrame;
}
}
}
public void update() {
if (isMoving) {
manXPos = manXPos + runSpeedPerSecond / fps;
if (manXPos > getWidth()) {
manYPos += (int) frameHeight;
manXPos = 10;
}
if (manYPos + frameHeight > getHeight()) {
manYPos = 10;
}
}
}
public void manageCurrentFrame() {
long time = System.currentTimeMillis();
if (isMoving) {
if (time > lastFrameChangeTime + frameLengthInMillisecond) {
lastFrameChangeTime = time;
currentFrame++;
if (currentFrame >= frameCount) {
currentFrame = 0;
}
}
}
frameToDraw.left = currentFrame * frameWidth;
frameToDraw.right = frameToDraw.left + frameWidth;
}
public void draw() {
if (ourHolder.getSurface().isValid()) {
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
whereToDraw.set((int) manXPos, (int) manYPos, (int) manXPos + frameWidth, (int) manYPos + frameHeight);
manageCurrentFrame();
canvas.drawBitmap(bitmapRunningMan, frameToDraw, whereToDraw, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch(InterruptedException e) {
Log.e("ERR", "Joining Thread");
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN :
isMoving = !isMoving;
break;
}
return true;
}
}
}
Now, you have just to run the application on your Android emulator or on your real device and to enjoy your Running Man Game Animation.
Don't hesitate to try this code and give me your feedbacks.
Thanks.
Sylvain
I just started learning self taught Android development and hopefully, I get to this level one days. Thanks for sharing your steps for this
Sent from my Nexus 6P using Tapatalk
nighthawk626 said:
I just started learning self taught Android development and hopefully, I get to this level one days. Thanks for sharing your steps for this
Sent from my Nexus 6P using Tapatalk
Click to expand...
Click to collapse
Great . I plan to make some tutorials for beginners too. Do you have some suggestions for that kind of tutorials ?
No suggestions, I'm just looking for a good place to begin. I first started with Android development then I scaled back to learn about Java, and still no luck, so I just started off with c++. Lol
Sent from my Nexus 6P using Tapatalk