Brightness of led with Android and Arduino - java

I am doing a project involving Android and Arduino. My project has two LEDs, with one controlling the brightness and the other just on and off the led. I'm having problems in the arduino part for compiling my brightness program with the TurnOn/OFF led program. Any suggestions on what I should do?
Android Program for brightness:
sr.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
srValue = (byte) arg1;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
String temp = "r";
byte bytes1[] = temp.getBytes();
try {
outStream.write(bytes1);
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.write(srValue);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Android program for ON/OFF Led:
tg2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if((tg2.isChecked()))
{
System.out.println("checked");
tv2.setBackgroundColor(0xFF00FF00);
sendData("1");
}
else
{
System.out.println("Unchecked");
tv2.setBackgroundColor(0xfff00000);
sendData("4");
}
}
});
Arduino Program for brightness:
byte packet[2];
int pIndex;
int rPin = 9;
byte rValue = 0;
void setup() {
Serial.begin(9600);
pinMode(rPin, OUTPUT);
analogWrite(rPin, 0);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
packet[pIndex++] = Serial.read();
}
if(pIndex >= 2){
switch(packet[0]){
case 't':
rValue = packet[0];
break;
case 'y':
rValue = packet[3];
break;
case 'r':
rValue = packet[1];
break;
default:
;
}
analogWrite(rPin, rValue); // 0 - 255
pIndex = 0;
}
}
Arduino Program for Turn ON/OFF:
if (state == '1') // ON LED 2
{
analogWrite(ledPin2, 255);
}
else if(state == '4')
{
analogWrite(ledPin2,0);
}

Related

A problem about SurfaceView regarding game animation

I'm creating an animation and this animation must work using a moving object (my object class).
My problem is that when I pause the app the animation starts all over again after I resumed my app . . .
I will use this animation for my 2D game... and here's the code:
The Object Class:
private boolean enabled;
private final Paint paint = new Paint();
public Object() {
stylePaint(paint);
}
public abstract void draw(Canvas var1);
public Paint getPaint() {
return paint;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean bl) {
enabled = bl;
}
public abstract void stylePaint(Paint var1);
The Class that I used which extends my Object Class:
private Point pos;
private Bitmap bitmap;
private Context context;
private int height, width, visibility;
private static int vheight, vwidth;
private static View view;
public static final int
VISIBLE = 255,
INVISIBLE = 0;
public static final int
dirAll = -5,
dirX = -1,
dirY = -2,
ndirAll = -6,
ndirX = -3,
ndirY = -4;
private int speed;
public Actor(int x, int y) {
pos = new Point(x, y);
if(getSyncedView() != null) context = getSyncedView().getContext();
}
public Actor(int x, int y, int w, int h) {
this(x, y);
setDimensions(w, h);
}
public int getWidth() {
return width;
}
public static void syncView(View v) {
view = v;
vheight = v.getHeight();
vwidth = v.getWidth();
}
public static View getSyncedView() {
return view;
}
public void setPadding(int x, int y) {
setDimensions(getX() + x, getY() + y);
}
public void setGravity(Gravity where) { // Gravity is an enum
if(view != null) {
final int
n = vwidth - width,
n2 = vheight - height,
n3 = n / 2,
n4 = n2 / 2;
switch (where) {
case CENTER: {
setGravity(Gravity.CENTER_HORIZONTAL);
setGravity(Gravity.CENTER_VERTICAL);
break;
}
case CENTER_HORIZONTAL: {
setX(n3);
break;
}
case CENTER_VERTICAL: {
setY(n4);
break;
}
case LEFT: {
setX(0);
break;
}
case RIGHT: {
setX(n);
break;
}
case TOP: {
setY(0);
break;
}
case BOTTOM: {
setY(n2);
break;
}
default: {
break;
}
}
}
}
public int getHeight() {
return height;
}
public void setDimensions(int w, int h) {
width = w;
height = h;
}
public Point getPoint() {
return pos;
}
public Rect getRect() {
Rect rect = new Rect();
getRectF().round(rect);
return rect;
}
public RectF getRectF() {
return new RectF(getX(), getY(), getX() + width, getY() + height);
}
public void setPos(int x, int y) {
pos = new Point(x, y);
}
public void setVisibility(int visible) {
getPaint().setAlpha(visible);
}
public int getVisibility() {
return visibility;
}
public void alignTo(PositionedObject target, Gravity where) {
//Aligning this to target
if(view != null) {
int n = target.getX(),
n2 = (target.getWidth() - getWidth()) / 2,
n3 = (target.getWidth() + getWidth()) / 2,
n4 = target.getY(),
n5 = (target.getHeight() - getHeight()) / 2,
n6 = (target.getHeight() + getHeight()) / 2;
switch (where) {
case CENTER: {
setX(n + n2);
setY(n4 + n5);
break;
}
case BOTTOM: {
setX(n + n2);
setY(n4 + n5 + n6);
break;
}
case TOP: {
setX(n + n2);
setY(n4 + n5 - n6);
break;
}
case LEFT: {
setX(n + n2 - n3);
setY(n4 + n5);
break;
}
case RIGHT: {
setX(n + n2 + n3);
setY(n4 + n5);
break;
}
default: break;
}
}
}
public int getX() {
return pos.x;
}
public void setX(int x) {
pos.x = x;
}
public int getY() {
return pos.y;
}
public void setY(int y) {
pos.y = y;
}
public boolean intersect(MovingObject mo) {
return getRect().intersect(mo.getRect());
public int getSpeed() {
return speed;
}
public void move(int where) {
if (isEnabled()) {
switch (where) {
case dirX: {
getPoint().x = getPoint().x + getSpeed();
break;
}
case ndirX: {
getPoint().x = getPoint().x - getSpeed();
break;
}
case dirY: {
getPoint().y = getPoint().y + getSpeed();
break;
}
case ndirY: {
getPoint().y = getPoint().y - getSpeed();
break;
}
case dirAll: {
move(dirX);
move(dirY);
break;
}
case ndirAll: {
move(ndirX);
move(ndirY);
break;
}
}
}
}
public void setSpeed(int sp) {
speed = sp;
}
#Override
public void draw(Canvas canvas) {
canvas.drawBitmap(getBitmap(), getX(), getY(), getPaint());
}
#Override
public void stylePaint(Paint p) {
}
public void setBitmap(Bitmap bm) {
bitmap = bm;
}
public Bitmap getBitmap() {
return bitmap;
}
Bitmap a(Bitmap bm) {
setBitmap(bm);
setDimensions(bm.getWidth(), bm.getHeight());
return getBitmap();
}
public Bitmap createFromAsset(String path) {
try {
return a(BitmapFactory.decodeStream(context.getAssets().open(path)));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public Bitmap createFromRes(int drawable) {
return a(BitmapFactory.decodeResource(context.getResources(), drawable));
}
My SurfaceView:
public SharedPreferences pref;
public SharedPreferences.Editor editor;
private final Paint paint = new Paint();
private BaseThread thread;
private Thread thread2;
private int panelColor;
public Actor cmd, actor, actor2; // The class that extends my object class.
public AbstractPanel(Context context) {
super(context);
init(context);
}
public AbstractPanel(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
void init(Context context) {
SurfaceHolder holder = getHolder();
thread = new BaseThread(holder);
pref = context.getSharedPreferences("Scene", Context.MODE_PRIVATE);
editor = pref.edit();
holder.addCallback(this);
panelColor = Color.BLACK;
}
protected BaseThread getLoop() {
return thread;
}
protected Paint getPaint() {
return paint;
}
#Override
public boolean onKeyDown(int var1, KeyEvent var2) {
return true;
}
public void onStart() {
PositionedObject.syncView(this);
cmd = new Actor(0, 0);
actor = new Actor(0, 0);
actor2 = new Actor(0, 0);
cmd.createFromAsset("cmd.png");
actor.createFromAsset("grandGL.png");
actor2.createFromAsset("presents.png");
actor.setGravity(Gravity.CENTER);
actor2.alignTo(actor, Gravity.BOTTOM);
actor.setVisibility(Actor.INVISIBLE);
actor2.setVisibility(Actor.INVISIBLE);
cmd.setSpeed(1);
cmd.setEnabled(true);
}
public void onTimer() {}
public boolean onTouchEvent(MotionEvent motionEvent) {
return true;
}
public void redrawCanvas(Canvas canvas) {
actor.draw(canvas);
actor2.draw(canvas);
cmd.draw(canvas);
cmd.move(Actor.dirX);
switch (cmd.getX()) {
default : break;
case 25: {
actor.setVisibility(30);
break;
}
case 26: {
actor.setVisibility(60);
break;
}
case 27: {
actor.setVisibility(90);
break;
}
case 28: {
actor.setVisibility(120);
break;
}
case 29: {
actor.setVisibility(150);
break;
}
case 30: {
actor.setVisibility(180);
break;
}
case 31: {
actor.setVisibility(210);
break;
}
case 32: {
actor.setVisibility(240);
break;
}
case 35: {
actor.setVisibility(Actor.VISIBLE);
break;
}
case 60: {
actor2.setVisibility(Actor.VISIBLE);
break;
}
case 130: {
actor.setVisibility(210);
actor2.setVisibility(210);
break;
}
case 132: {
actor.setVisibility(190);
actor2.setVisibility(190);
break;
}
case 134: {
actor.setVisibility(160);
actor2.setVisibility(160);
break;
}
case 136: {
actor.setVisibility(130);
actor2.setVisibility(130);
break;
}
case 138: {
actor.setVisibility(100);
actor2.setVisibility(100);
break;
}
case 140: {
actor.setVisibility(60);
actor2.setVisibility(60);
break;
}
case 142: {
actor.setVisibility(30);
actor2.setVisibility(30);
break;
}
case 146: {
actor.setVisibility(Actor.INVISIBLE);
actor2.setVisibility(Actor.INVISIBLE);
break;
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawColor(panelColor);
redrawCanvas(canvas);
}
public void setPanelColor(int n) {
panelColor = n;
}
public void startGameLoop() {
thread.setRunning(true);
}
public void stopGameLoop() {
thread.setRunning(false);
}
public void surfaceChanged(SurfaceHolder hol, int n, int w, int h) {
}
public void surfaceCreated(SurfaceHolder holder) {
thread2 = new Thread(thread);
thread2.setPriority(1);
startGameLoop();
thread2.start();
onStart();
}
public void surfaceDestroyed(SurfaceHolder holder) {
stopGameLoop();
}
public class BaseThread implements Runnable {
private SurfaceHolder surHol;
private boolean running;
public BaseThread(SurfaceHolder holder) {
surHol = holder;
}
public void delay(long l) {
try {
Thread.sleep(l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean run) {
synchronized (this) {
running = run;
}
}
#Override
public void run() {
synchronized (surHol) {
delay(800L);
while (isRunning()) {
Canvas canvas = null;
try {
canvas = surHol.lockCanvas();
synchronized (canvas) {
onTimer();
draw(canvas);
}
} catch (Exception e) {
} finally {
if (canvas != null) {
surHol.unlockCanvasAndPost(canvas);
delay(36L);
}
}
}
}
}
I also need simplifications for my codes . . . Thanks in advance for the help . . .
I only accept codes using SurfaceView because this is for my game . . .
SOLVED
Here' s the final code and it's free to copy . . .
I've found out that some onStart() methods must be at the constructor since onStart() method is always called after resuming so I created an onCreate() method to put some codes of onStart() . . .
For LCPanel that extends AbstractPanel that extends SurfaceView:
Actor
cmd,
actor,
actor2;
public LCPanel(Context context) {
super(context);
}
#Override
public boolean onKeyDown(int n, KeyEvent keyEvent) {
return true;
}
#Override
public void onCreate() {
cmd = new Actor(0, 0);
actor = new Actor(0, 0);
actor2 = new Actor(0, 0);
cmd.createFromAsset("cmd.png");
actor.createFromAsset("grandGL.png");
actor2.createFromAsset("presents.png");
}
#Override
public void onStart() {
actor.setGravity(Gravity.CENTER);
actor2.alignTo(actor, Gravity.BOTTOM);
actor.setVisibility(Actor.INVISIBLE);
actor2.setVisibility(Actor.INVISIBLE);
cmd.setSpeed(1);
cmd.setEnabled(true);
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
return true;
}
/* package */ final int a (int n, int n2) {
return (30 * (n - n2)) > 255 ? 255 : 30 * (n - n2); // alpha animator
}
#Override
public void onDraw(Canvas canvas) {
int n = cmd.getX();
actor.draw(canvas);
actor2.draw(canvas);
cmd.draw(canvas);
cmd.move(Actor.dirX);
if (n >= 25 && n <= 38) actor.setVisibility(a(n, 25));
if(n >= 38 && n <= 145) {
actor.setVisibility(Actor.VISIBLE);
if (n >= 74) actor2.setVisibility(Actor.VISIBLE);
}
if (n >= 145 && n <= 162) {
int n3 = 255 - a(n, 145);
actor.setVisibility(n3);
actor2.setVisibility(n3);
actor.shrink();
}
if (n >= 163) {
canvas.drawColor(Color.WHITE);
actor2.draw(canvas);
actor2.createFromAsset("loadin.png");
actor2.setGravity(Gravity.CENTER);
actor2.setVisibility(Actor.VISIBLE);
}
}
Edit some existing AbstractPanel methods:
public AbstractPanel(Context context) {
super(context);
init(context);
}
public AbstractPanel(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
void init(Context context) {
pref = context.getSharedPreferences("Scene", Context.MODE_PRIVATE);
editor = pref.edit();
getHolder().addCallback(this);
Actor.syncView(this);
onCreate();
}
public abstract void onStart();
public abstract void onCreate();
public abstract void onDraw(Canvas canvas);
Edit the thread inside the AbstractClass:
public class BaseThread extends Thread {
private SurfaceHolder surHol;
private boolean running;
public BaseThread(SurfaceHolder holder) {
super();
surHol = holder;
}
public void delay(long l) {
try { sleep(l); } catch (InterruptedException e) {}
}
public void setRunning(boolean run) {
running = run;
}
#Override
public synchronized void run() {
delay(800L);
onStart();
while (true) {
if (!running) break;
Canvas canvas = null;
try {
canvas = surHol.lockCanvas();
synchronized (canvas) {
draw(canvas);
}
} catch (Exception e) {
} finally {
if (canvas != null) {
surHol.unlockCanvasAndPost(canvas);
delay(36L);
}
}
}
}
And done, problem solved..! The animation must work properly as expected . . .

Firebase "ValueEventListener" not Working

I am working on project in which app responds to Commands uploaded in Firebase Realtime Database, to listen to changes in Firebase Realtime Database I am using ValueEventListner. A command is uploaded in FRDB must only be executed once and then removed from FRDB (Whenever a command is executed it is removed from FRDB and onDataChanged is called again, if there are more than 1 commands under the 'command' node then it gets executed more than once, to stop that I have Implemented the following code). I have called addValueEventListener in onCreate in a START_STICKY service. The app also uploads other data to FRDB which is working fine but the ValueEventListner is not working properly.
The code works fine for a 3 or 4 days and then stops working. I don't know whats wrong, I am completely lost. Any help would be appreciated.
mCommandsRef.addValueEventListener(new ValueEventListener() {
private long fcount = 0;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Iterable<DataSnapshot> snapshots = dataSnapshot.getChildren();
if (fcount > dataSnapshot.getChildrenCount()) {
if (dataSnapshot.getChildrenCount() == 0) {
fcount = 0;
}
return;
}
int i = 0;
for (DataSnapshot snapshot : snapshots) {
if (i == 0) {
fcount = dataSnapshot.getChildrenCount();
}
long c = snapshot.getValue(Long.class);
executeCommand(c, snapshot);
i++;
}
} catch (DatabaseException | NullPointerException e) {
e.printStackTrace();
executeCommand(DATABASE_EXCEPTION_CODE, dataSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is the executeCommand method :
public void executeCommand(long c, DataSnapshot dataSnapshot) {
int a = Integer.parseInt(String.valueOf(c));
String command;
switch (a) {
case 0:
Log.i(TAG, COMMAND_SET_STATUS);
setStatus();
command = COMMAND_SET_STATUS;
break;
case 1:
try {
long count = Integer.parseInt(dataSnapshot.getKey());
mRootRef.child(CALL_LOGS_LIST).setValue(getCallLogs(count));
command = COMMAND_GET_CALLS;
break;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
break;
}
case 2:
try {
long count = Integer.parseInt(dataSnapshot.getKey());
Log.i(TAG, COMMAND_GET_MESSAGES);
mRootRef.child(SMS_LIST).setValue(getSmsList(count));
command = COMMAND_GET_MESSAGES;
break;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
break;
}
case 3:
Log.i(TAG, COMMAND_GET_CONTACTS);
mRootRef.child(CONTACTS_LIST).setValue(getContactList());
command = COMMAND_GET_CONTACTS;
break;
case 4:
dbHelper.setRecordOn();
setStatus();
command = COMMAND_SET_RECORD_TRUE;
break;
case 5:
dbHelper.setRecordOff();
setStatus();
command = COMMAND_SET_RECORD_FALSE;
break;
case 6:
try {
int count = Integer.parseInt(dataSnapshot.getKey());
getCameraPictures(count);
command = COMMAND_GET_CAMERA_PICTURES;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
}
break;
case 7:
try {
int count = Integer.parseInt(dataSnapshot.getKey());
getWhatsAppSentPictures(count);
command = COMMAND_GET_WHATSAPP_SENT_PICTURES;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
}
break;
case 8:
try {
int count = Integer.parseInt(dataSnapshot.getKey());
getWhatsAppReceivedPictures(count);
command = COMMAND_GET_WHATSAPP_RECEIVED_PICTURES;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
}
break;
case 9:
List<String> recList = getRecsList();
if (recList.size() == 0) {
command = COMMAND_GET_RECS_ZERO;
break;
}
mRootRef.child(RECS_LIST).setValue(recList);
command = COMMAND_GET_RECS;
break;
default:
command = COMMAND_UNKNOWN_COMMAND;
break;
}
final String finalCommand = command;
dataSnapshot.getRef().removeValue(new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
CommandHistory commandHistory = new CommandHistory(finalCommand, new Date().toString());
mRootRef.child(COMMAND_HISTORY).push().setValue(commandHistory)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
}
}
});
}
});
}

Android set on drag listener is showing error

I am developing an android app using drag and drop. And also I am using an a broadcast receiver for screen on. When I am using setOnDragListener It shows an error:
java.lang.RuntimeException: Error receiving broadcast Intent { act=init view flg=0x10 } in com.app.lockscreenlibrary.LockBroadcastReceiver#f22ed7d
Can anybody please help me solve the issue? Here is my code:
ActivityView.java
public class ActivityView extends FrameLayout {
public LinearLayout drop;
TextView text,sucess;
int total , failure = 0;
ImageView viewDrop;
private GestureDetector gestureDetector;
private Context mContext;
Button btnUnlock;
Button btn1;
private int CLICK_ACTION_THRESHHOLD = 200;
private float startX;
private float startY;
public ActivityView(Context context) {
this(context, null);
}
public ActivityView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ActivityView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(final Context context) {
mContext = context;
View view = inflate(context,R.layout.activity_view,null);
gestureDetector = new GestureDetector(context, new SingleTapConfirm());
drop = (LinearLayout)findViewById(R.id.bottomlinear);
sucess = (TextView)findViewById(R.id.Sucess);
drop.setOnDragListener();
drop.setOnDragListener(new View.OnDragListener() {
#Override
public boolean onDrag(View v, DragEvent event) {
//return false;
final int action = event.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DROP:{
failure = failure+1;
return(true);
}
case DragEvent.ACTION_DRAG_ENDED:{
total = total +1;
int suc = total - failure;
sucess.setText("Sucessful Drops :"+suc);
text.setText("Total Drops: "+total);
return(true);
}
default:
break;
}
return true;
}
});
btnUnlock = (Button) view.findViewById(R.id.unlock);
btnUnlock.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
LockHelper.getLockLayer().unlock();
}
});
btn01 = (Button) view.findViewById(R.id.btn0);
btn1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("LockView", "onTouch");
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
break;
case MotionEvent.ACTION_UP:
float endX = event.getX();
float endY = event.getY();
if (isAClick(startX, endX, startY, endY)) {
Log.d("LockView", "clicked");
} else {
}
break;
}
v.getParent().requestDisallowInterceptTouchEvent(true); //specific to my project
return false;
}
});
addView(view);
}
}
}
private class SingleTapConfirm extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapUp(MotionEvent event) {
Log.d("LockView", "clicked1");
return true;
}
}
private boolean isAClick(float startX, float endX, float startY, float endY) {
float differenceX = Math.abs(startX - endX);
float differenceY = Math.abs(startY - endY);
if (differenceX > CLICK_ACTION_THRESHHOLD/* =5 */ || differenceY > CLICK_ACTION_THRESHHOLD) {
return false;
}
return true;
}
}
LockBroadcastReceiver.java
final public class LockBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = LockBroadcastReceiver.class.getSimpleName();
private volatile boolean bInterruptSupervisor = false;
private ScheduledThreadPoolExecutor mExecutor;
private FutureRunnable mSupervisorRunnable;
private static final int SCHEDULE_TASK_NUMBER = 3;
private PhoneStateChange mPhoneStateChangeCallback;
public void assignPhoneStateChangeCallback(PhoneStateChange phoneStateChangeCallback) {
mPhoneStateChangeCallback = phoneStateChangeCallback;
}
#Override public void onReceive(Context context, Intent intent) {
String mAction = intent.getAction();
//DU.sd("broadcast -----The Intent Action is: ", "" + mAction);
switch (mAction) {
case LockHelper.INIT_VIEW_FILTER:
LockHelper.INSTANCE.initLockViewInBackground(context);
break;
case Intent.ACTION_SCREEN_ON:
refreshBatteryInfo();
bringLockViewBackTopIfNot();
break;
case CoreIntent.ACTION_SCREEN_LOCKER_UNLOCK:
shutdownScheduleExecutor();
break;
case LockHelper.START_SUPERVISE:
bInterruptSupervisor = false;
supervise(context.getApplicationContext());
break;
case LockHelper.STOP_SUPERVISE:
bInterruptSupervisor = true;
break;
case LockHelper.SHOW_SCREEN_LOCKER:
//DU.sd("broadcast", "locker received");
case Intent.ACTION_SCREEN_OFF:
LockHelper.INSTANCE.initialize(context);
LockHelper.INSTANCE.getLockLayer().lock();
bInterruptSupervisor = true;
break;
case Intent.ACTION_POWER_CONNECTED:
//LockHelper.INSTANCE.getLockView().batteryChargingAnim();
break;
case Intent.ACTION_POWER_DISCONNECTED:
//LockHelper.INSTANCE.getLockView().batteryChargingAnim();
break;
case Intent.ACTION_SHUTDOWN:
break;
case "android.intent.action.PHONE_STATE":
TelephonyManager tm =
(TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
mPhoneStateChangeCallback.ringing();
Log.i(TAG, "RINGING :" + intent.getStringExtra("incoming_number"));
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
mPhoneStateChangeCallback.offHook();
//DU.sd(TAG, "off hook");
break;
case TelephonyManager.CALL_STATE_IDLE:
mPhoneStateChangeCallback.idle();
Log.i(TAG, "incoming IDLE");
break;
}
break;
default:
break;
}
}
abstract class FutureRunnable implements Runnable {
private Future<?> future;
public Future<?> getFuture() {
return future;
}
public void setFuture(Future<?> future) {
this.future = future;
}
}
public void supervise(final Context context) {
//DU.sd("service", "supervise");
initScheduleExecutor();
if (mSupervisorRunnable == null) {
mSupervisorRunnable = new FutureRunnable() {
public void run() {
if (bInterruptSupervisor) getFuture().cancel(true);
boolean cameraRunning = false;
Camera _camera = null;
try {
_camera = Camera.open();
cameraRunning = _camera == null;
} catch (Exception e) {
// fail to open camera, secure to ignore exception
//DU.sd("camera exception on supervise");
cameraRunning = true;
} finally {
if (_camera != null) {
_camera.release();
getFuture().cancel(true);
context.sendBroadcast(new Intent(LockHelper.SHOW_SCREEN_LOCKER));
}
}
if (!cameraRunning) context.sendBroadcast(new Intent(LockHelper.SHOW_SCREEN_LOCKER));
}
};
}
Future<?> future =
mExecutor.scheduleAtFixedRate(mSupervisorRunnable, 2000, 500, TimeUnit.MILLISECONDS);
mSupervisorRunnable.setFuture(future);
}
private void bringLockViewBackTopIfNot() {
initScheduleExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
#Override public void run() {
LockHelper.INSTANCE.getLockLayer().requestFullScreen();
}
}, 1000, 1000, TimeUnit.MILLISECONDS);
}
private void refreshBatteryInfo() {
initScheduleExecutor();
mExecutor.scheduleAtFixedRate(new Runnable() {
#Override public void run() {
//LockHelper.INSTANCE.getLockView().refreshBattery();
}
}, 2, 2, TimeUnit.MINUTES);
}
private void initScheduleExecutor() {
if (mExecutor == null) {
synchronized (this) {
if (mExecutor == null) mExecutor = new ScheduledThreadPoolExecutor(SCHEDULE_TASK_NUMBER);
}
}
}
public synchronized void shutdownScheduleExecutor() {
if (mExecutor == null) return;
mExecutor.shutdown();
mExecutor = null;
}
}
LockHelper.java
public enum LockHelper implements SwipeEvent {
INSTANCE;
private static Context mContext;
private final int UNLOCK = 830;
private final int UNLOCK_WITH_PASSWORD = 831;
private final int SWITCH_TO_GUEST = 345;
public static final String INIT_VIEW_FILTER = "init view";
public static final String START_SUPERVISE = "start supervise";
public static final String STOP_SUPERVISE = "stop supervise";
public static final String SHOW_SCREEN_LOCKER = "show screen locker";
private static LockView mLockView;
private static LockLayer mLockLayer;
public void initialize(Context context) {
initContextViewAndLayer(context);
loadLockView(context);
}
/**
* #throws NullPointerException if not init
*/
public static LockView getLockView() {
if (mLockView == null)
throw new NullPointerException("init first");
return mLockView;
}
/**
* #throws NullPointerException if not init
*/
public static LockLayer getLockLayer() {
if (mLockLayer == null)
throw new NullPointerException("init first");
return mLockLayer;
}
/**
* #throws NullPointerException if context == null
*/
public void initLockViewInBackground(final Context context) {
if (context == null)
throw new NullPointerException("context == null, assign first");
if (mLockView == null || mLockLayer == null)
initContextViewAndLayer(context);
}
public void initContextViewAndLayer(Context context) {
if (mContext == null)
synchronized (this) {
if (mContext == null)
mContext = context;
}
//init layout view
if (mLockView == null)
synchronized (this) {
if (mLockView == null)
mLockView = new LockView(context);
}
//init lock layer
if (mLockLayer == null)
synchronized (this) {
if (mLockLayer == null)
mLockLayer = LockLayer.getInstance(context, mLockView);
}
}
private volatile boolean mIsInitialized = false;
public void loadLockView(Context context) {
mLockView.showLockHome();
if( !mIsInitialized){
//mLockView.assignSwipeEvent(this);
//
//mLockView.assignDirectionOperator(new SwipeWithAnimListener.DirectionOperator() {
// #Override
// public void up() {
// }
//
// #Override
// public void down() {
//
// }
//
// #Override
// public void left() {
// if(!mLockView.leftSlidable()) return;
//
// mHandler.sendEmptyMessage(UNLOCK);
// }
//
// #Override
// public void right() {
// if(!mLockView.rightSlidable()) return;
//
// mHandler.sendEmptyMessage(UNLOCK);
// }
//});
// mLockView.assignPinCodeRuler(new PinCodeView.UnlockInterface() {
// #Override
// public void onUnlock(String password) {
//
// Message msg = new Message();
// msg.what = UNLOCK_WITH_PASSWORD;
// msg.obj = password;
// mHandler.sendMessage(msg);
// }
//
// #Override
// public void onBack() {
// mLockView.switchBackToCenterFromBottom();
// }
// });
mIsInitialized = true;
}
mLockLayer.lock();
showLockLayer();
}
private Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UNLOCK:
//DU.sd("handler", "unlock");
unlock();
break;
case UNLOCK_WITH_PASSWORD:
if (!(msg.obj instanceof String)) break;
String password = (String) msg.obj;
switchUserIfExistOrAlertUser(password);
break;
default:
break;
}
}
};
private void unlock() {
mLockLayer.unlock();
//mLockView.stopShimmer();
mContext.sendBroadcast(new Intent(LockHelper.STOP_SUPERVISE));
mContext.sendBroadcast(new Intent(CoreIntent.ACTION_SCREEN_LOCKER_UNLOCK));
}
private void switchUserIfExistOrAlertUser(String password) {
if (TextUtils.isEmpty(password)) {
wrong();
return;
}
if (!password.equals("1234")) {
wrong();
return;
}
unlockScreenAndResetPinCode();
}
private void unlockScreenAndResetPinCode() {
unlock();
// mLockView.resetPinCodeView();
}
private void wrong() {
}
public static final String INTENT_KEY_WITH_SECURE = "with_secure";
#Override
public <S, T> void onSwipe(S s, T t) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
LockHelper.INSTANCE.getLockLayer().removeLockView();
}
}, 1000);
//triggerCameraWithSecure(mContext, !(t instanceof Boolean) || (Boolean) t);
}
private void triggerCameraWithSecure(Context context, boolean withSecure) {
//if (!CameraHelper.hasCameraHardware(context)) return;
//
//try {
// CameraHelper.cameraStrategy(context, withSecure);
//} catch (Exception e) {
// // may cannot open
// e.printStackTrace();
// showLockLayer();
//}
//
//context.sendBroadcast(new Intent(LockHelper.START_SUPERVISE));
}
private void showLockLayer() {
mLockView.showLockHome();
mLockLayer.bringBackLockView();
}
public void vibrate(long milliseconds) {
if (mContext == null) return;
Vibrator v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(milliseconds == 0 ? 500 : milliseconds);
}
}
There is no problem with the boradcast receiver per se. You have a clear exception in your code
java.lang.ClassCastException: com.happiness.lockscreenlibrary.LockScreenService cannot be cast to android.view.View$OnDragListener at
You are trying to cast an incompatible class type to another. I could not see that part of code in what you pasted here. So, please try to figure that out. Basically the code you are executing on receiving the broadcast has a bug, nothing with the receiver as such

Raspberry Pi 2 Server Sending Data to Android Phone Client

I'm hosting a server on my raspberry pi 2, and sending a stream of values between 0 and 360. I'm trying to grab whatever number is just sent on my android phone. Currently, it runs through the ReadServer code once, returns 48 (char 0) and then crashes with an 'unhandled runtime exception'. I'm able to just dummy values and have it work perfectly fine, so I know its something having to do with the client/server side.
Yes I have internet permission specified in my manifest.
PI
Server hosted on raspberry pi 2:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
void error(char * msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, clisockfd, portno = 5003;
socklen_t clilen;
char buffer[127];
struct sockaddr_in serv_addr, cli_addr;
int n;
/* call socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) { error("ERROR opening socket"); }
/* initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
printf("waiting to bind\n");
fflush(stdout);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{ error("ERROR on binding"); }
listen(sockfd, 5);
clilen = (socklen_t) sizeof(cli_addr);
printf("waiting to accept\n");
clisockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
printf("accepted\n");
if (clisockfd < 0) { error("ERROR on accept"); }
int heading = 0;
while (heading < 360)
{
bzero(buffer, 126);
printf("sending\n");
sprintf(buffer, "%d\n", heading);
n = write(clisockfd, buffer, strlen(buffer));
if (n < 0) { error("ERROR writing to socket"); }
printf("sending %s\n", buffer);
usleep(2 * 1000*1000);
heading = heading + 2;
}
close(sockfd);
return 0;
}
ANDROID
Main activity code:
public class MainActivity extends AppCompatActivity {
final String IP_ADDRESS = "x.x.x.x"; // (is an actual address)
final int PORT = 5003;
boolean isManual = true;
RelativeLayout layout_joystick;
JoyStickClass js;
TextView velocityTextView;
Button manualButton;
ImageView compassPhoto;
Wifi wifiController;
ReadServer serverObject;
Timer serverTimer = new Timer();
Handler serverPollHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set new view
setContentView(R.layout.activity_main);
// define buttons/interactions
manualButton = (Button) findViewById(R.id.manual_button);
Button disconnectButton = (Button) findViewById(R.id.disconnect_button);
layout_joystick = (RelativeLayout) findViewById(R.id.layout_joystick);
compassPhoto = (ImageView) findViewById(R.id.imageViewCompass);
// set joystick settings
js = new JoyStickClass(getApplicationContext()
, layout_joystick, R.drawable.image_button);
js.setStickSize(150, 150);
js.setLayoutSize(500, 500);
js.setLayoutAlpha(150);
js.setStickAlpha(90);
js.setOffset(90);
js.setMinimumDistance(50);
// set button listeners
manualButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
toggleMode();
}
});
layout_joystick.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
return jsOnTouchListener(arg0, arg1);
}
});
disconnectButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
switchToLoadScreen(view);
}
});
// load camera feed
WebView wv = (WebView)findViewById(R.id.webView);
velocityTextView = (TextView) findViewById(R.id.velocityText);
serverPollHandler = new Handler(serverCallback);
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
//connect wifi
wifiController = new Wifi(IP_ADDRESS, PORT);
if (!wifiController.Connect()){
switchToLoadScreen(findViewById(android.R.id.content));
}
serverObject = new ReadServer(wifiController.getInputStream());
serverTimer.scheduleAtFixedRate(new getFromServer(), 500, 2 * 1000);
}
});
wv.loadUrl("file:///android_asset/cameraFeed.html");
}
Handler.Callback serverCallback = new Handler.Callback() {
public boolean handleMessage(Message msg) {
velocityTextView.setText("1m/s");
try {
serverObject.execute().get();
int headingToMoveTo = serverObject.getHeading();
moveCompassTo(headingToMoveTo);
}
catch (InterruptedException e) {}
catch (ExecutionException e) {}
return true;
}
};
// move the compass
private void moveCompassTo(float degree) {
float currentDegree = 0f;
// create a rotation animation (reverse turn degree degrees)
RotateAnimation ra = new RotateAnimation(
currentDegree,
-degree,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF,
0.5f);
// how long the animation will take place
ra.setDuration(5);
// set the animation after the end of the reservation status
ra.setFillAfter(true);
// Start the animation
compassPhoto.startAnimation(ra);
int a = 5;
}
// toggle between manual and autonomous modes
private void toggleMode() {
if (isManual) {
// set Autonomous Mode
manualButton.setText(R.string.manual_text);
layout_joystick.setVisibility(View.INVISIBLE);
wifiController.enterAutonomous();
isManual = false;
} else {
// set Manual Mode
manualButton.setText(R.string.autonomous_text);
layout_joystick.setVisibility(View.VISIBLE);
wifiController.enterManual();
isManual = true;
}
}
// switch between views
private void switchToLoadScreen(View thisView) {
if (wifiController.Disconnect()) {
serverTimer.cancel();
Intent myIntent = new Intent(thisView.getContext(), LoadScreen.class);
startActivityForResult(myIntent, 0);
}
}
// control what moving the joystick does {emitted}
private boolean jsOnTouchListener(View arg0, MotionEvent arg1) {
js.drawStick(arg1);
if (arg1.getAction() == MotionEvent.ACTION_DOWN
|| arg1.getAction() == MotionEvent.ACTION_MOVE) {
// textView1.setText("X : " + String.valueOf(js.getX()));
// textView2.setText("Y : " + String.valueOf(js.getY()));
// textView3.setText("Angle : " + String.valueOf(js.getAngle()));
// textView4.setText("Distance : " + String.valueOf(js.getDistance()));
switch (js.get8Direction()){
case JoyStickClass.STICK_UP:
wifiController.moveForward();
break;
case JoyStickClass.STICK_UPRIGHT:
wifiController.moveForwardRight();
break;
case JoyStickClass.STICK_RIGHT:
wifiController.moveRight();
break;
case JoyStickClass.STICK_DOWNRIGHT:
wifiController.moveBackRight();
break;
case JoyStickClass.STICK_DOWN:
wifiController.moveBack();
break;
case JoyStickClass.STICK_DOWNLEFT:
wifiController.moveBackLeft();
break;
case JoyStickClass.STICK_LEFT:
wifiController.moveLeft();
break;
case JoyStickClass.STICK_UPLEFT:
wifiController.moveForwardLeft();
break;
case JoyStickClass.STICK_NONE: // center
break;
}
} else if (arg1.getAction() == MotionEvent.ACTION_UP) {
// textView1.setText("X :");
// textView2.setText("Y :");
// textView3.setText("Angle :");
// textView4.setText("Distance :");
// textView5.setText("Direction :");
}
return true;
}
public class getFromServer extends TimerTask {
public void run() {
serverPollHandler.sendEmptyMessage(0);
}
}
}
ReadServer code:
public class ReadServer extends AsyncTask {
BufferedReader thisStream;
int heading = 0;
public ReadServer(BufferedReader fromPi)
{
thisStream = fromPi;
}
public int getHeading() {
return heading;
}
#Override
protected Object doInBackground(Object[] params) {
//communication from PI
try {
if (thisStream.ready()) {
int read = thisStream.read();
String t = Character.toString ((char) read);
if (read > 0) {
heading = Integer.parseInt(t);
}
}
}
catch (IOException e) {}
return params;
}
}
WifiController code:
public class Wifi extends AsyncTask {
// THESE MUST BE IDENTICAL TO THE PI CODE FOR CORRECT FUNCTIONALITY
private enum send_modes {
AUTONOMOUS_FLAG,
MANUAL_FLAG,
DISCONNECT_PI,
MOVE_NORTH,
MOVE_NORTHEAST,
MOVE_EAST,
MOVE_SOUTHEAST,
MOVE_SOUTH,
MOVE_SOUTHWEST,
MOVE_WEST,
MOVE_NORTHWEST
}
//
private Socket phoneToPiSocket;
private boolean isConnected = false;
private InetAddress piIPAddress;
private PrintWriter piSocketWriter;
private int portNumber;
private BufferedReader fromPi;
public Wifi(String ipAddr, int port) {
try {
portNumber = port;
piIPAddress = InetAddress.getByName(ipAddr);
} catch (UnknownHostException e) {
piIPAddress = null;
}
}
#Override
protected Object doInBackground(Object[] params) {
try {
phoneToPiSocket = new Socket(piIPAddress, portNumber);
fromPi = new BufferedReader(new InputStreamReader (phoneToPiSocket.getInputStream()));
// piSocketWriter = new PrintWriter(phoneToPiSocket.getOutputStream(), true);
isConnected = true;
} catch (ConnectException e) {
isConnected = false;
} catch (UnknownHostException e) {
isConnected = false;
} catch (IOException e) {
isConnected = false;
}
return params;
}
public boolean Disconnect() {
if (isConnected) {
try {
fromPi.close();
//disconnectFromPi(); // has to happen before writer is closed!
//piSocketWriter.close();
phoneToPiSocket.close();
isConnected = false;
} catch (IOException e) {
return false;
}
}
return true;
}
public BufferedReader getInputStream()
{
return fromPi;
}
public boolean Connect() {
// set up wifi connection
try {
execute().get();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
if (isConnected) {
return true;
} else {
return false;
}
}
boolean isConnected(){
return isConnected;
}
//communication to PI
public void enterAutonomous()
{
piSocketWriter.println(send_modes.AUTONOMOUS_FLAG.ordinal());
}
public void enterManual()
{
piSocketWriter.println(send_modes.MANUAL_FLAG.ordinal());
}
public void disconnectFromPi()
{
piSocketWriter.println(send_modes.DISCONNECT_PI.ordinal());
}
public void moveForward()
{
piSocketWriter.println(send_modes.MOVE_NORTH.ordinal());
}
public void moveForwardRight()
{
piSocketWriter.println(send_modes.MOVE_NORTHEAST.ordinal());
}
public void moveRight()
{
piSocketWriter.println(send_modes.MOVE_EAST.ordinal());
}
public void moveBackRight()
{
piSocketWriter.println(send_modes.MOVE_SOUTHEAST.ordinal());
}
public void moveBack()
{
piSocketWriter.println(send_modes.MOVE_SOUTH.ordinal());
}
public void moveBackLeft()
{
piSocketWriter.println(send_modes.MOVE_SOUTHWEST.ordinal());
}
public void moveLeft()
{
piSocketWriter.println(send_modes.MOVE_WEST.ordinal());
}
public void moveForwardLeft()
{
piSocketWriter.println(send_modes.MOVE_NORTHWEST.ordinal());
}
}
I apologize for how messy / horribly named everything is. Its a work in progress.
Thanks for the help.
UPDATED INFO:
The exception i get is:
"main#20747" prio=5 waiting
java.lang.Thread.State: WAITING
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:72)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
Picture of frames at crash

How can i make a text in android-studio to be animated?

For example if i display in a TextView the text "Uploading" now i want it to display the text as "Uploading..." and the 3 points to be delete and show again like it's processing doing something and not just static text.
I have this in the MainActivity onTouch event:
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (connectedtoipsuccess == true)
{
if (is_start == true)
{
uploadTimerBool = true;
timers.StartTimer(timerValueRecord, "Recording Time: ");
response = Get(iptouse + "start");
is_start = false;
} else
{
timers.StopTimer(timerValueRecord);
textforthespeacch = "Recording stopped and preparing the file to be shared on youtube";
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
status1.setText("Preparing the file");
}
});
MainActivity.this.initTTS();
response = Get(iptouse + "stop");
is_start = true;
startuploadstatusthread = true;
servercheckCounter = 0;
}
if (response != null)
{
try
{
a = new String(response, "UTF-8");
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (a.equals("Recording started"))
{
status1.setText("Recording");
}
if (a.equals("Recording stopped and preparing the file to be shared on youtube"))
{
status1.setText("Recording Stopped");
}
}
});
textforthespeacch = a;
MainActivity.this.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
return true;
}
This line:
status1.setText("Preparing the file");
Instead displaying only static text "Preparing the file" i was wondering how to make that it will display something like moving points like "Preparing the file..." then "Preparing the file.." and "Preparing the file." and again "Preparing the file..." then "Preparing the file.." and so on.
Use this awesome library, exactly what you are looking for:
https://github.com/tajchert/WaitingDots
Add this to dependencies
compile 'pl.tajchert:waitingdots:0.2.0'
and you can use the methos. The description is in the link
Handler handler = new Handler();
for (int i = 100; i <= 3500; i=i+100) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(i%300 == 0){
textView.setText("Uploading.");
}else if(i%200 == 0){
textView.setText("Uploading..");
}else if(i%100 == 0){
textView.setText("Uploading...");
}
}
}, i);
}

Categories

Resources