Android SlidingMenu nullpointer on toggle - java

I've implemented an SlidingMenu, I set it up with SlidingMenu sm = getSlidingMenu() in the activity I want to use the menu. The problem I've got I want to toggle it via a button I've created on a canvas. If I click these area on the canvas it will stop drawing and open the sliding menu - works until here. But then I added some content with an linearlayout and a textview in it, on clicking the textview the text changes (kind of menu to change some options). And after it changed once the next click should toggle the sliding menu again.
I've created the behind view's in another class, and triggered a method in the activity containing the slidingmenu, it looks like this:
public void toggleSM() {
Thread splash = new Thread(new Runnable() {
#SuppressWarnings("static-access")
#Override
public void run() {
try {
Thread.currentThread().sleep(500);
getSlidingMenu().toggle(true);
Thread.currentThread().sleep(1000);
animateButton.setLeftState(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
splash.start();
}
I added the sleep to avoid any problems caused by the sm animation or changing content, the aninamteButton is to trigger the drawing of the canvas again. But it throws a nullpointer exception. With and without animation of the slidingmenu.
EDIT:
The two classes I'm using:
public class Ingame extends SlidingActivity implements OnTouchListener{
private LeftMenu lm;
private SlidingMenu sm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sh = new ScreenHandler(this);
fh = new FilesHandler(this);
animateMap = new AnimateMap(this);
ch = new CoordsHandler(this);
animateButton = new AnimateButton();
sched = new Schedule();
lm = new LeftMenu(this);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setupViews();
lm.setupLeftMenu();
setBehindContentView(lm.getLayout());
setupSlidingMenu();
}
#Override
protected void onPause() {
super.onPause();
gb.pause();
}
#Override
protected void onResume() {
super.onResume();
gb.resume();
}
#SuppressWarnings("deprecation")
public void setupViews() {
FrameLayout fl = new FrameLayout(getBaseContext());
LayoutParams sizeP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
fl.setLayoutParams(sizeP);
fl.setBackgroundColor(Color.rgb(0, 153, 204));
gb = new GameBoard(getBaseContext());
LayoutParams fillP = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
gb.setLayoutParams(fillP);
gb.setOnTouchListener(Ingame.this);
fl.addView(gb);
setContentView(fl);
}
public void setupSlidingMenu() {
sm = getSlidingMenu();
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
sm.setMenu(lm.getLayout());
}
#SuppressWarnings("static-access")
#Override
public boolean onTouch(View v, MotionEvent e) {
float distX, distY;
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = e.getX();
startY = e.getY();
gb.movedDist.put("startX", startX);
gb.movedDist.put("startY", startY);
finX = finY = -1;
gb.movedDist.put("finX", finX);
gb.movedDist.put("finY", finY);
break;
case MotionEvent.ACTION_MOVE:
finX = e.getX();
finY = e.getY();
distX = startX - finX;
distY = startY - finY;
if(!checkUnvalidValues() && (Math.abs(distX) > sh.getTSize() || Math.abs(distY) > sh.getTSize())) {
int rectDistX = (int) (distX/sh.getTSize());
int rectDistY = (int) (distY/sh.getTSize());
noMove = false;
if(!checkEdges(rectDistX, rectDistY)) {
animateMap.animateXYDistance(rectDistX, rectDistY);
startX = e.getX();
startY = e.getY();
}
}
break;
case MotionEvent.ACTION_UP:
finX = e.getX();
finY = e.getY();
if(checkButton() == IngameButton.PP) {
animateButton.changePPState();
break;
}
if(checkButton() == IngameButton.LEFT) { //WHERE I TRIGGER THE SLIDINGMENU
animateButton.setLeftState(true);
if(!animateButton.getPPState())
animateButton.setPPState(true);
sm.toggle(true);
lm.openLeftMenu();
break;
}
if(noMove && !checkUnvalidValues())
animateMap.tellCoordinate(finX, finY);
noMove = true;
break;
}
return true;
}
private boolean checkUnvalidValues() {
if(startX <= sh.getSideSize()-1 || startX >= (sh.getScreenWidth()-sh.getSideSize()))
return true;
if(startY <= -1 || startY >= (sh.getScreenHeight()-sh.getBottomGUISize()))
return true;
if(finX <= sh.getSideSize()-1 || finX >= (sh.getScreenWidth()-sh.getSideSize()))
return true;
if(finY <= -1 || finY >= (sh.getScreenHeight()-sh.getBottomGUISize()))
return true;
return false;
}
public SlidingMenu getSM() {
return sm;
}
public void toggleSM() {
runOnUiThread(new Runnable() {
#SuppressWarnings("static-access")
#Override
public void run(){
getSlidingMenu().toggle(true);
SlidingMenu sm = getSlidingMenu();
sm.getAlpha();
try {
Thread.currentThread().sleep(1000);
animateButton.setLeftState(false);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
});
}
LeftMenu:
public class LeftMenu {
private Context context;
private Ingame ingame;
private AnimateButton animateButton;
private LinearLayout ll;
private LinearLayout.LayoutParams llp;
private static LeftMenuPage page;
private static int buttonTextSize = 15;
public LeftMenu(Context context) {
this.context = context;
ingame = new Ingame();
animateButton = new AnimateButton();
}
public void setupLeftMenu() {
page = LeftMenuPage.OVERVIEW;
setupLinearLayout();
setupButtons();
}
#SuppressWarnings("deprecation")
private void setupLinearLayout() {
ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setBackgroundColor(0xff000000);
llp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);
ll.setLayoutParams(llp);
}
public LinearLayout getLayout() {
return ll;
}
private void setupButtons() {
final TextView t1 = new TextView(context);
t1.setBackgroundColor(0xff000000);
t1.setTextColor(0xffffffff);
t1.setTypeface(null, Typeface.NORMAL);
t1.setTextSize(buttonTextSize);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight = 1.0f;
lp.gravity=1;
t1.setLayoutParams(lp);
String content = null;
if(page == LeftMenuPage.OVERVIEW) {
content = "Creation Mode";
}
else {
content = "Back";
}
t1.setText(content);
ll.addView(t1);
t1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
t1.setTextColor(0xffcccccc);
switch(page) {
case OVERVIEW:
page = LeftMenuPage.CREATE;
t1.setText("Create Dwarves");
ingame.toggleSM();
if(!animateButton.getPPState())
animateButton.setPPState(true);
break;
case CREATE:
ingame.toggleSM();
if(!animateButton.getPPState())
animateButton.setPPState(true);
break;
}
t1.setTextColor(0xffffffff);
}
});
}
public void openLeftMenu() {
page = LeftMenuPage.OVERVIEW;
}
}
EDIT 2:
05-10 15:14:53.535: E/AndroidRuntime(25064): FATAL EXCEPTION: main
05-10 15:14:53.535: E/AndroidRuntime(25064): java.lang.NullPointerException
05-10 15:14:53.535: E/AndroidRuntime(25064): at com.jeremyfeinstein.slidingmenu.lib.app.SlidingActivity.getSlidingMenu(SlidingActivity.java:104)
05-10 15:14:53.535: E/AndroidRuntime(25064): at me.G4meM0ment.DwarvenSkill.Ingame$1.run(Ingame.java:234)
05-10 15:14:53.535: E/AndroidRuntime(25064): at android.os.Handler.handleCallback(Handler.java:615)
05-10 15:14:53.535: E/AndroidRuntime(25064): at android.os.Handler.dispatchMessage(Handler.java:92)
05-10 15:14:53.535: E/AndroidRuntime(25064): at android.os.Looper.loop(Looper.java:137)
05-10 15:14:53.535: E/AndroidRuntime(25064): at android.app.ActivityThread.main(ActivityThread.java:4918)
05-10 15:14:53.535: E/AndroidRuntime(25064): at java.lang.reflect.Method.invokeNative(Native Method)
05-10 15:14:53.535: E/AndroidRuntime(25064): at java.lang.reflect.Method.invoke(Method.java:511)
05-10 15:14:53.535: E/AndroidRuntime(25064): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
05-10 15:14:53.535: E/AndroidRuntime(25064): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
05-10 15:14:53.535: E/AndroidRuntime(25064): at dalvik.system.NativeStart.main(Native Method)
StackTrace, as I already mentionen in some comments, getSlidingMenu returns null and mHelper (SlidingActivityHelper) causes this because it's null

getSlidingMenu().toggle(true);
has to run on the UI Thread. Move it inside and Handler or if your are inside an Activity use
runOnUiThread(new Runnable() {
public void run(){
getSlidingMenu().toggle(true);
}
});

Related

Trying to create LifecycleCamera with destroyed lifecycle

I'm trying to make floating cameraview for my screen recorder application.
FloatingViewService.java
public class FloatingViewService extends LifecycleService implements CameraXConfig.Provider, LifecycleOwner {
private View mFloatingView;
private WindowManager mWindowManager;
PreviewView previewView;
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
public FloatingViewService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return null;
}
#Override
public void onCreate() {
super.onCreate();
mFloatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_widget, null);
final WindowManager.LayoutParams params;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
} else {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
}
params.width = 400;
params.height = 300;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView, params);
mFloatingView.findViewById(R.id.previewFrame).setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
//this code is helping the widget to move around the screen with fingers
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
mWindowManager.updateViewLayout(mFloatingView, params);
return true;
}
return false;
}
});
cameraFun(mFloatingView);
}
public void cameraFun(View mFloatingView) {
previewView = mFloatingView.findViewById(R.id.previewFrame);
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
}
}, ContextCompat.getMainExecutor(this));
}
void bindPreview(#NonNull ProcessCameraProvider cameraProvider) {
Preview preview = new Preview.Builder()
.build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_FRONT)
.build();
preview.setSurfaceProvider(previewView.createSurfaceProvider());
OrientationEventListener orientationEventListener = new OrientationEventListener(this) {
#Override
public void onOrientationChanged(int orientation) {
int rotation;
int orientationcheck = getResources().getConfiguration().orientation;
if (orientationcheck == Configuration.ORIENTATION_PORTRAIT) {
if (orientation >= 45 && orientation < 135) {
rotation = 360;
} else if (orientation >= 135 && orientation < 225) {
rotation = 180;
} else if (orientation >= 225 && orientation < 315) {
rotation = 360;
} else {
rotation = 0;
}
Log.i("orientation", String.valueOf(orientation) + "= ORIENTATION_PORTRAIT" + orientationcheck);
} else {
if (orientation >= 45 && orientation < 135) {
rotation = 90;
} else if (orientation >= 135 && orientation < 225) {
rotation = 180;
} else if (orientation >= 225 && orientation < 315) {
rotation = 270;
} else {
rotation = 0;
}
Log.i("orientation", String.valueOf(orientation) + "= ORIENTATION_Land" + orientationcheck);
}
Log.i("orientation", String.valueOf(orientation) + "= " + orientationcheck);
previewView.setRotation(rotation);
}
};
orientationEventListener.enable();
cameraProvider.bindToLifecycle(this, cameraSelector, preview);
}
#NonNull
#Override
public CameraXConfig getCameraXConfig() {
return Camera2Config.defaultConfig();
}
public void onDestroy() {
super.onDestroy();
mWindowManager.removeView(mFloatingView);
}
}
layout_floating_widget.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.camera.view.PreviewView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/previewFrame"
android:layout_width="300dp"
android:layout_height="250dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_gravity="center" />
BackgroundService.java Check below code how I call FloatingViewService.java
public class BackgroundService extends Service {
Boolean onoff = true;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
new FloatingViewService();
if (onoff) {
onoff = false;
startService(new Intent(this, FloatingViewService.class));
} else {
onoff = true;
stopService(new Intent(this, FloatingViewService.class));
}
}
}
ERROR:
java.lang.IllegalArgumentException: Trying to create LifecycleCamera with destroyed lifecycle.
at androidx.camera.lifecycle.LifecycleCameraRepository.createLifecycleCamera(LifecycleCameraRepository.java:103)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:414)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:275)
at com.rdbrain.FloatingViewService.bindPreview(FloatingViewService.java:196)
at com.rdbrain.FloatingViewService.lambda$cameraFun$0$FloatingViewService(FloatingViewService.java:138)
at com.rdbrain.-$$Lambda$FloatingViewService$qkM-fNI79D-TvnilmrNFZjQYwlI.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6626)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
Note : This code is working as separate module but when I connect to screen recorder it not working, I have setup all necessary permission and service in manifests.xml
Use viewLifecycleOwner instead of this in cameraProvider.bindToLifecycle(this, cameraSelector, preview);

Android setOnDragListener shows error

I am developing an android app of screen lock. I have used broadcast receiver for screen. In my app I want to use drag and drop. So, 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.
And the library file reference is https://github.com/find-happiness/LockScreen
when i am using drop.setOnDragListener(new View.OnDragListener() { in LockView.java file . Then the error may occur. I want to get the dragged item value. (Here is my item is btn0 and the drag portion is bottomlinear)
My code is LockView.java:
public class LockView extends FrameLayout {
public LinearLayout drop;
TextView text, sucess;
int total, failure = 0;
ImageView viewDrop;
private GestureDetector gestureDetector;
private Context mContext;
Button btnUnlock;
Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnH, btnS;
Button buttonB;
private int CLICK_ACTION_THRESHHOLD = 200;
private float startX;
private float startY;
int nums[] = new int[4];
int position = 0;
ImageView imageView1, imageView2, imageView3, imageView4;
public LockView(Context context) {
this(context, null);
}
public LockView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LockView(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_screen_lock, null);
gestureDetector = new GestureDetector(context, new SingleTapConfirm());
drop = (LinearLayout) findViewById(R.id.bottomlinear);
sucess = (TextView) findViewById(R.id.Sucess);
drop.setOnDragListener(new View.OnDragListener() {
#Override
public boolean onDrag(View v, DragEvent event) {
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();
}
});
btn0 = (Button) view.findViewById(R.id.btn0);
btn1 = (Button) view.findViewById(R.id.btn1);
btn2 = (Button) view.findViewById(R.id.btn2);
btn3 = (Button) view.findViewById(R.id.btn3);
btn4 = (Button) view.findViewById(R.id.btn4);
btn5 = (Button) view.findViewById(R.id.btn5);
btn6 = (Button) view.findViewById(R.id.btn6);
btn7 = (Button) view.findViewById(R.id.btn7);
btn8 = (Button) view.findViewById(R.id.btn8);
btn9 = (Button) view.findViewById(R.id.btn9);
btnH = (Button) view.findViewById(R.id.btnH);
btnS = (Button) view.findViewById(R.id.btnS);
imageView1 = (ImageView) view.findViewById(R.id.imageView);
imageView2 = (ImageView) view.findViewById(R.id.imageView2);
imageView3 = (ImageView) view.findViewById(R.id.imageView3);
imageView4 = (ImageView) view.findViewById(R.id.imageView4);
buttonB = (Button) view.findViewById(R.id.buttonB);
btn0.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 0;
}
setPosition(position);
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 2;
}
setPosition(position);
}
});
btn3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 3;
}
setPosition(position);
}
});
btn4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 4;
}
setPosition(position);
}
});
btn5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 5;
}
setPosition(position);
}
});
btn6.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 6;
}
setPosition(position);
}
});
btn7.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 7;
}
setPosition(position);
}
});
btn8.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 8;
}
setPosition(position);
}
});
btn9.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position > -1 && position < 4) {
nums[position] = 9;
}
setPosition(position);
}
});
btn1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent arg1) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadow = new View.DragShadowBuilder(btn1);
v.startDrag(data, shadow, v, 0);
Log.d("LOGTAG", "onTouch");
return true;
}
});
if (position == 3) {
checkSpeedDial();
} else if (position == 2) {
checkSpeedDial();
} else if (position == 1) {
checkSpeedDial();
} else if (position == 0) {
checkSpeedDial();
} else if (position == -1) {
checkSpeedDial();
}
buttonB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (position == 1) {
imageView1.setImageResource(0);
position--;
Log.d("LOGTAG", "clicked1 : position =" + position);
} else if (position == 2) {
imageView2.setImageResource(0);
position--;
Log.d("LOGTAG", "clicked2 : position =" + position);
} else if (position == 3) {
imageView3.setImageResource(0);
position--;
Log.d("LOGTAG", "clicked3 : position =" + position);
} else if (position == 4) {
imageView4.setImageResource(0);
position--;
Log.d("LOGTAG", "clicked4 : position =" + position);
} else {
}
}
});
if (position > 3) {
checkPassword();
}
addView(view);
}
private void setPosition(int pos) {
if (pos == 0) {
imageView1.setImageResource(R.drawable.lock_circle);
position++;
} else if (pos == 1) {
imageView2.setImageResource(R.drawable.lock_circle);
position++;
} else if (pos == 2) {
imageView3.setImageResource(R.drawable.lock_circle);
position++;
} else if (pos == 3) {
imageView4.setImageResource(R.drawable.lock_circle);
position++;
checkPassword();
} else {
}
}
public void showLockHome() {
}
private void checkSpeedDial() {
Log.d("LOGTAG", position + " ::" + nums[0] + " 2: " + nums[1] + " 3: " + nums[2] + " 4: " + nums[3]);
}
public void checkPassword() {
Log.d("LOGTAG", "1 :" + nums[0] + " 2: " + nums[1] + " 3: " + nums[2] + " 4: " + nums[3]);
int pas[] = new int[4];
pas[0] = 1;
pas[1] = 1;
pas[2] = 1;
pas[3] = 1;
if (Arrays.equals(nums, pas)) {
LockHelper.getLockLayer().unlock();
} else {
Log.d("LOGTAG", "Wrong Password");
}
}
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;
}
}
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);
}
public static LockView getLockView() {
if (mLockView == null)
throw new NullPointerException("init first");
return mLockView;
}
public static LockLayer getLockLayer() {
if (mLockLayer == null)
throw new NullPointerException("init first");
return mLockLayer;
}
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);
}
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){
mIsInitialized = true;
}
mLockLayer.lock();
showLockLayer();
}
private Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 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();
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();
}
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);
}
private void triggerCameraWithSecure(Context context, boolean withSecure) { }
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);
}
}
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();
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) {
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) {
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;
}
}
activity_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:patternview="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_screen_lock"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="1"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:minWidth="10dp"/>
<LinearLayout
android:id="#+id/bottomlinear"
android:gravity="center"
android:background="#00ffff"
android:orientation="vertical"
android:layout_marginTop="50dp"
android:layout_height="75dp"
android:layout_width="75dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Sucess"
android:textSize="20sp" />
</LinearLayout>
</RelativeLayout>
The error shows :
E/AndroidRuntime: FATAL EXCEPTION: main Process:
com.yudong.fitnewdome, PID: 8020 java.lang.RuntimeException: Error
receiving broadcast Intent { act=init view flg=0x10 } in
com.happiness.lockscreenlibrary.LockBroadcastReceiver#f22ed7d at
android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:880)
at android.os.Handler.handleCallback(Handler.java:739) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:135) at
android.app.ActivityThread.main(ActivityThread.java:5312) at
java.lang.reflect.Method.invoke(Native Method) at
java.lang.reflect.Method.invoke(Method.java:372) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:90
1) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.ClassCastException:
com.happiness.lockscreenlibrary.LockScreenService cannot be cast to
android.view.View$OnDragListener at
com.happiness.lockscreenlibrary.view.LockView.init(LockView.java:89)
at com.happiness.lockscreenlibrary.view.LockView.(LockView.java:73)
at com.happiness.lockscreenlibrary.view.LockView.(LockView.java:0) at
com.happiness.lockscreenlibrary.view.LockView.(LockView.java:0) at
com.happiness.lockscreenlibrary.util.LockHelper.initContextViewAndLayer(LockH
elper.java:82) at
com.happiness.lockscreenlibrary.util.LockHelper.initLockViewInBackground(Lock
Helper.java:68) at
com.happiness.lockscreenlibrary.LockBroadcastReceiver.onReceive(LockBroadcast
Receiver.java:55) at
android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:870)
at android.os.Handler.handleCallback(Handler.java:739) at
android.os.Handler.dispatchMessage(Handler.java:95) at
android.os.Looper.loop(Looper.java:135) at
android.app.ActivityThread.main(ActivityThread.java:5312) at
java.lang.reflect.Method.invoke(Native Method) at
java.lang.reflect.Method.invoke(Method.java:372)
How to solve the issue please help me.
The fix is to use:
drop = (LinearLayout) view.findViewById(R.id.bottomlinear);
instead of:
drop = (LinearLayout) findViewById(R.id.bottomlinear);

How to have static dialog fragment method to use throughout app in Android?

I have created a DialogFragment class that I need to show from within a onDragListener. I tried a regular AlertDialog but couldn't get the activity context to be static. I tried adding this to my onDragListener class and to my CustomLayoutClass but it says that getSupportFragmentManager() cannot be referenced from a static method or that it cannot be resolved.
public static void showScoopDialog() {
FragmentManager fm = getSupportFragmentManager();
ScoopSizeDialog editNameDialogFragment = ScoopSizeDialog.newInstance("Some Title");
editNameDialogFragment.show(fm, "fragment_edit_name");
}
This is my custom onDragListener class. I need to show a dialog with edittext when the user drops an image:
public class ChoiceDragListener implements View.OnDragListener {
boolean DEBUG = true;
Context context;
public String TAG = "Drag Layout:";
public ChoiceDragListener(Context context) {
this.context = context;
}
#Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
if(DEBUG) Log.v("here","drag started");
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_LOCATION:
int mCurX = (int) event.getX();
int mCurY = (int) event.getY();
if (DEBUG) Log.v("Cur(X, Y) : " ,"here ::" + mCurX + ", " + mCurY );
break;
case DragEvent.ACTION_DRAG_EXITED:
if (DEBUG)
Log.v("here","drag exits");
break;
case DragEvent.ACTION_DROP:
//handle the dragged view being dropped over a drop view
View view = (View) event.getLocalState();
ClipData cd = event.getClipData();
ClipData.Item item = cd.getItemAt(0);
String resp = item.coerceToText(context).toString();
//view dragged item is being dropped on
ImageView dropTarget = (ImageView) v;
//view being dragged and dropped
ImageView dropped = (ImageView) view;
dropped.setEnabled(false);
//if an item has already been dropped here, there will be a tag
Object tag = dropTarget.getTag();
CreateProd.nsList.add(dropped.getTag().toString());
Log.d(TAG, dropped.getTag().toString() + "added to list");
//if there is already an item here, set it back visible in its original place
if (tag != null) {
//the tag is the view id already dropped here
int existingID = (Integer)tag;
//set the original view visible again
((Activity) context).findViewById(existingID).setVisibility(View.VISIBLE);
}
break;
case DragEvent.ACTION_DRAG_ENDED:
if (DEBUG) Log.i("drag event", "ended::" + ChoiceTouchListener.offsetX + "," + ChoiceTouchListener.offsetY);
/**
* returning false so that goes to parentView onDrag function
*/
return false;
//break;
default:
break;
}
return true;
}
}
And this is my custom layout:
public class DragLayout extends RelativeLayout {
boolean DEBUG = true;
AnimationDrawable blenderAnim;
Handler handlerAnim2;
Context context;
private int dimensionInPixel = 200;
int screenWidth,screenHeight;
static float up_x=0,up_y=0;
boolean mIsScrolling = false;
public DragLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
//not to include in main program
getDimensionsofScreen();
setLayout();
setViews();
}
private void setLayout() {
// set according to parent layout (not according to current layout)
RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
rLp.topMargin = 2 * (screenHeight / 25); // calculating 1/10 of 4/5
// screen
this.setLayoutParams(rLp);
}
void setViews() {
ImageView img2 = new ImageView(context);
int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
RelativeLayout.LayoutParams rLp = new RelativeLayout.LayoutParams(
(screenWidth / 5), (screenHeight / 5));
rLp.topMargin = (screenHeight / 10);
rLp.leftMargin = (4*screenWidth / 10);
rLp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
img2.setLayoutParams(rLp);
img2.getLayoutParams().height = dimensionInDp;
img2.getLayoutParams().width = dimensionInDp;
img2.setImageDrawable(getResources().getDrawable(R.drawable.blender_anim));
img2.setOnDragListener(new ChoiceDragListener(context));
this.addView(img2);
blenderAnim = (AnimationDrawable)img2.getDrawable();
blenderAnim.setOneShot(true);
blenderAnim.stop();
}
public ArrayList<Integer> getDimensionsofScreen() {
//metrics that holds the value of height and width
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();;
ArrayList<Integer> vals = new ArrayList<Integer>();
vals.add(displayMetrics.widthPixels);
vals.add(displayMetrics.heightPixels);
screenHeight = displayMetrics.heightPixels;
screenWidth = displayMetrics.widthPixels;
return vals;
}
#SuppressLint("NewApi")
#Override
public boolean onDragEvent(DragEvent event) {
int mCurX = (int) event.getX();
int mCurY = (int) event.getY();
if (event.getAction() == DragEvent.ACTION_DRAG_STARTED || event.getAction() == DragEvent.ACTION_DRAG_ENTERED) {
if (blenderAnim.isRunning()) {
blenderAnim.stop();
} else {
blenderAnim.run();
handlerAnim2 = new Handler();
handlerAnim2.postDelayed(
new Runnable() {
#Override
public void run() {
blenderAnim.stop();
}},
getAnimationDuration(blenderAnim));
}
}
if (event.getAction() == DragEvent.ACTION_DROP || event.getAction() == DragEvent.ACTION_DRAG_EXITED) {
if (blenderAnim.isRunning()) {
blenderAnim.stop();
} else {
blenderAnim.run();
handlerAnim2 = new Handler();
handlerAnim2.postDelayed(
new Runnable(){
#Override
public void run() {
blenderAnim.stop();
}},
getAnimationDuration(blenderAnim));
}
Log.v("here", "it is :: " + mCurX + ", " + mCurY);
View view1 = (View) event.getLocalState();
view1.setVisibility(View.VISIBLE);
ObjectAnimator animationx = ObjectAnimator.ofFloat(view1,"translationX", mCurX - ChoiceTouchListener.offsetX-(screenWidth / 10),0.0f);
ObjectAnimator animationy = ObjectAnimator.ofFloat(view1, "translationY", mCurY - ChoiceTouchListener.offsetY - (screenHeight / 10), 0.0f);
AnimatorSet animSet = new AnimatorSet();
animSet.setDuration(500);
animSet.playTogether(animationx,animationy);
animSet.start();
}
if (event.getAction() == DragEvent.ACTION_DROP || event.getAction() == DragEvent.ACTION_DRAG_ENDED){
if (blenderAnim.isRunning()) {
blenderAnim.stop();
}
}
return true;
}
private int getAnimationDuration(AnimationDrawable src) {
int dur = 0;
for (int i = 0; i<src.getNumberOfFrames(); i++) {
dur += src.getDuration(i);
}
return dur;
}
private void showScoopDialog() {
FragmentManager fm = getSupportFragmentManager();
ScoopSizeDialog editNameDialogFragment = ScoopSizeDialog.newInstance("Some Title");
editNameDialogFragment.show(fm, "fragment_edit_name");
}
}

Error, if hide canvas-game

public class GameView extends SurfaceView
{
private GameThread mThread;
SurfaceHolder holder;
Bitmap fon = BitmapFactory.decodeResource(getResources(), R.drawable.fon);
ArrayList<Integer> lasers = new ArrayList<Integer>();
ArrayList<Integer> coordYlasers = new ArrayList<Integer>();
ArrayList<Integer> coordXlasers = new ArrayList<Integer>();
Bitmap laser = BitmapFactory.decodeResource(getResources(), R.drawable.laser);
int touchX = 0;
int touchY = 0;
int coordX = 0;
int coordY = 600;
int _coordX = 0;
private boolean running = false;
ArrayList<Bitmap> blocks = new ArrayList<Bitmap>();
public class GameThread extends Thread
{
private GameView view;
public GameThread(GameView view)
{
this.view = view;
}
public void setRunning(boolean run)
{
running = run;
}
public void run()
{
int i = 0;
while (running)
{
Canvas canvas = null;
try
{
canvas = view.getHolder().lockCanvas();
synchronized (view.getHolder())
{
onDraw(canvas);
}
}
catch (Exception e) { }
finally
{
if (canvas != null)
{
view.getHolder().unlockCanvasAndPost(canvas);
}
}
}
}
}
public GameView(Context context)
{
super(context);
mThread = new GameThread(this);
getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
mThread.setRunning(false);
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
mThread.setRunning(true);
mThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
});
}
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
_coordX = coordX;
X = (int) event.getX();
Y = (int) event.getY();
}
if(event.getAction() == MotionEvent.ACTION_MOVE)
{
touchX = ((int) event.getX());
touchY = (int) event.getY();
//if (Math.abs(touchX - X) > 10){
coordX = _coordX + (touchX - X);
invalidate();
//}
}
if(event.getAction() == MotionEvent.ACTION_UP)
{
_coordX = coordX;
Y = touchY;
}
return true;
}
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.setTextSize(20);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(fon, 0, 0, null);
canvas.drawBitmap(player, coordX, coordY, null);
canvas.drawBitmap(laser, coordLaserX, coordLaserY, null);
for (int i = 1; i<coordYlasers.size(); ++i){
canvas.drawBitmap(laser, coordXlasers.get(i), coordYlasers.get(i), null);
}
canvas.drawText("" + V, 10, 25, paint);
}
}
Application is worked excellent, but....
If I hide app, game crashes. Help, please.
Logcat error.
5553-5553/com.example.thetronuo.pregame E/AndroidRuntime﹕ FATAL
EXCEPTION: main
java.lang.IllegalThreadStateException: Thread already started.
at java.lang.Thread.start(Thread.java:1045)
at com.example.thetronuo.pregame.GameView$1.surfaceCreated(GameView.java:161)
at android.view.SurfaceView.updateWindow(SurfaceView.java:569)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:231)
at android.view.View.dispatchWindowVisibilityChanged(View.java:7618)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1211)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4356)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5099)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
at dalvik.system.NativeStart.main(Native Method)
It's activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GameView(this));
}
"wait()" - unhandled exception.
Where to write "resumeThread()"?
public class GameThread extends Thread
{
private GameView view;
private boolean pause = false;
private synchronized void check(){
while(pause){
wait();
}
}
public void pauseThread(){
pause = true;
}
public void resumeThread(){
pause = false;
notify();
}
public GameThread(GameView view)
{
this.view = view;
}
I think I had the same problem. But i fixed it.
Put a this in your Thread class:
private boolean pause = false;
private synchronized void check(){
while(pause){
wait();
}
}
public void pauseThread(){
pause = true;
}
public void resumeThread(){
pause = false;
notify();
}
And when onSurfaceDestroyed is called you need to pause the thread with the method youve created: pauseThread();
also call the method check(); in the while-loop, so:
while(true){
check();
... other code ...
}
and create a onResume() method in the activity class, so whenever the user turns back to the app, it will call this method automatically, and put this code into the method:
resumeThread();
I hope this would help you, im not sure if it is all the code you need as im not at home at the moment, if it doesnt work ill have a look and edit when im at home.

FATAL EXCEPTION: main android in google play services

I try to get current location and user activity, following the guide from
http://j.mp/io13-location the "checkpoint_final"
but i got those error when i run the program.
my logCat:
02-21 18:12:38.439: E/AndroidRuntime(3798): FATAL EXCEPTION: main
02-21 18:12:38.439: E/AndroidRuntime(3798): Process: com.android.google.codelab.location, PID: 3798
02-21 18:12:38.439: E/AndroidRuntime(3798): java.lang.RuntimeException: Unable to resume activity {com.android.google.codelab.location/com.android.google.codelab.location.LocationActivity}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.os.Handler.dispatchMessage(Handler.java:102)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.os.Looper.loop(Looper.java:136)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-21 18:12:38.439: E/AndroidRuntime(3798): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 18:12:38.439: E/AndroidRuntime(3798): at java.lang.reflect.Method.invoke(Method.java:515)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-21 18:12:38.439: E/AndroidRuntime(3798): at dalvik.system.NativeStart.main(Native Method)
02-21 18:12:38.439: E/AndroidRuntime(3798): Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.dk.bB(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.a(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm$c.bB(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fl.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.location.LocationClient.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.google.codelab.location.LocationActivity.restartLocationClient(LocationActivity.java:248)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.google.codelab.location.LocationActivity.onResume(LocationActivity.java:197)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.Activity.performResume(Activity.java:5310)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
02-21 18:12:38.439: E/AndroidRuntime(3798): ... 12 more
my Code
public class LocationActivity extends FragmentActivity {
public static String TAG = "LocationActivity";
public static boolean isAppForeground = false;
private static final int ERROR_DIALOG_ON_CREATE_REQUEST_CODE = 4055;
private static final int ERROR_DIALOG_ON_RESUME_REQUEST_CODE = 4056;
// Shared variables
private GoogleMap mMap;
private Dialog errorDialog;
// Location Request variables
private LocationClient mLocationClient;
private TextView mLocationStatus;
private LocationCallback mLocationCallback = new LocationCallback();
private Location mLastLocation;
private static final int LOCATION_UPDATES_INTERVAL = 10000; // Setting 10 sec interval for location updates
// Activity Recognition variables
private ActivityRecognitionClient mActivityRecognitionClient;
private ActivityRecognitionCallback mActivityRecognitionCallback = new ActivityRecognitionCallback();
public static final String ACTION_ACTIVITY_RECOGNITION =
"com.android.google.codelab.location.LocationActivity.ACTIVITY_RECOGNITION";
private static final int ACTIVITY_UPDATES_INTERVAL = 4000;
private PendingIntent mActivityRecognitionPendingIntent;
private Switch mSwitch;
private ActivityRecognitionIntentReceiver mActivityRecognitionIntentReceiver;
// Geo Fencing variables
private GeoFenceCallback mGeoFenceCallback = new GeoFenceCallback();
private int id = 0;
private static final float GEOFENCE_RADIUS = 100;
private HashMap<String, Circle> mGeoFences;
private HashMap<String, Circle> mTriggeringFences;
public static final String ACTION_GEOFENCE =
"com.android.google.codelab.location.LocationActivity.GEOFENCE";
private TextView mGeoFenceStatus;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkGooglePlayServiceAvailability(ERROR_DIALOG_ON_CREATE_REQUEST_CODE);
}
private void init() {
// Initialize map
if (mMap == null) {
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment myMapFragment =
(SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
mMap = myMapFragment.getMap();
}
// Initialize Location Client
mLocationStatus = (TextView) findViewById(R.id.location_status);
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, mLocationCallback, mLocationCallback);
Log.v(LocationActivity.TAG, "Location Client connect");
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
mLocationClient.connect();
}
}
// Initialize Action Recognition
if (mActivityRecognitionClient == null) {
mActivityRecognitionClient =
new ActivityRecognitionClient(this,
mActivityRecognitionCallback, mActivityRecognitionCallback);
}
mSwitch = (Switch) findViewById(R.id.swtich);
mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startActivityDetection(buttonView);
} else {
stopActivityDetection(buttonView);
}
}
});
if (mActivityRecognitionIntentReceiver == null) {
mActivityRecognitionIntentReceiver = new ActivityRecognitionIntentReceiver();
registerReceiver(mActivityRecognitionIntentReceiver,
new IntentFilter(LocationActivity.ACTION_ACTIVITY_RECOGNITION));
}
// Initialize Geo Fencing
mGeoFenceStatus = (TextView) findViewById(R.id.geo_fence_status);
if (mGeoFences == null) {
mGeoFences = new HashMap<String, Circle>();
}
if (mTriggeringFences == null) {
mTriggeringFences = new HashMap<String, Circle>();
}
// Setup map to allow adding Geo Fences
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.setOnMapLongClickListener(mGeoFenceCallback);
}
#Override
public void onPause() {
super.onPause();
// Indicate the application is in background
isAppForeground = false;
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(mLocationCallback);
mLocationClient.disconnect();
}
}
#Override
public void onResume() {
super.onResume();
// Indicate the application is in foreground
isAppForeground = true;
checkGooglePlayServiceAvailability(ERROR_DIALOG_ON_RESUME_REQUEST_CODE);
restartLocationClient();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mActivityRecognitionIntentReceiver);
mActivityRecognitionIntentReceiver = null;
}
private void checkGooglePlayServiceAvailability(int requestCode) {
// Query for the status of Google Play services on the device
int statusCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (statusCode == ConnectionResult.SUCCESS) {
init();
} else {
if (GooglePlayServicesUtil.isUserRecoverableError(statusCode)) {
errorDialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
this, requestCode);
errorDialog.show();
} else {
// Handle unrecoverable error
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ERROR_DIALOG_ON_CREATE_REQUEST_CODE:
init();
break;
case ERROR_DIALOG_ON_RESUME_REQUEST_CODE:
restartLocationClient();
break;
}
}
}
private void restartLocationClient() {
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
mLocationClient.connect(); // Somehow it becomes connected here
return;
}
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem menuItem = menu.add(R.string.clear_map);
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
clearMap();
return true;
}
});
return true;
}
public void clearMap() {
mMap.clear();
mLastLocation = null;
mGeoFenceCallback.removeGeoFences();
}
private class LocationCallback implements ConnectionCallbacks, OnConnectionFailedListener,
LocationListener {
#Override
public void onConnected(Bundle connectionHint) {
Log.v(LocationActivity.TAG, "Location Client connected");
// Display last location
Location location = mLocationClient.getLastLocation();
if (location != null) {
handleLocation(location);
}
// Request for location updates
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
#Override
public void onDisconnected() {
Log.v(LocationActivity.TAG, "Location Client disconnected by the system");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(LocationActivity.TAG, "Location Client connection failed");
}
#Override
public void onLocationChanged(Location location) {
if (location == null) {
Log.v(LocationActivity.TAG, "onLocationChanged: location == null");
return;
}
// Add a marker iff location has changed.
if (mLastLocation != null &&
mLastLocation.getLatitude() == location.getLatitude() &&
mLastLocation.getLongitude() == location.getLongitude()) {
return;
}
handleLocation(location);
}
private void handleLocation(Location location) {
// Update the mLocationStatus with the lat/lng of the location
Log.v(LocationActivity.TAG, "LocationChanged == #" +
location.getLatitude() + "," + location.getLongitude());
mLocationStatus.setText("Location changed #" + location.getLatitude() + "," +
location.getLongitude());
// Add a marker of that location to the map
LatLng latlongzoom = new LatLng(location.getLatitude(),
location.getLongitude());
String snippet = location.getLatitude() + "," + location.getLongitude();
Marker marker = mMap.addMarker(
new MarkerOptions().position(latlongzoom));
marker.setSnippet(snippet);
marker.setTitle(snippet);
// Center the map to the first marker
if (mLastLocation == null) {
mMap.moveCamera(CameraUpdateFactory.
newCameraPosition(CameraPosition.fromLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()),
(float) 16.0)));
}
mLastLocation = location;
}
};
public void startActivityDetection(View v) {
if (!mActivityRecognitionClient.isConnected()) {
mActivityRecognitionClient.connect();
}
}
public void stopActivityDetection(View v) {
if (mActivityRecognitionClient.isConnected()) {
mActivityRecognitionClient.removeActivityUpdates(mActivityRecognitionPendingIntent);
mActivityRecognitionClient.disconnect();
}
}
private class ActivityRecognitionCallback implements ConnectionCallbacks, OnConnectionFailedListener {
#Override
public void onConnected(Bundle connectionHint) {
Log.v(LocationActivity.TAG, "Activity Recognition Client connected");
// Request activity updates
Intent intent = new Intent(LocationActivity.this,
ActivityRecognitionIntentService.class);
intent.setAction(LocationActivity.ACTION_ACTIVITY_RECOGNITION);
mActivityRecognitionPendingIntent = PendingIntent.getService(LocationActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mActivityRecognitionClient.requestActivityUpdates(ACTIVITY_UPDATES_INTERVAL,
mActivityRecognitionPendingIntent);
}
#Override
public void onDisconnected() {
Log.v(LocationActivity.TAG, "Activity Recognition Client disconnected by the system");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(LocationActivity.TAG,
"Activity Recognition Client connection failed " + result.getErrorCode());
}
};
private class GeoFenceCallback implements OnMapLongClickListener,
OnAddGeofencesResultListener, OnRemoveGeofencesResultListener {
#Override
public void onMapLongClick(LatLng point) {
Log.v(LocationActivity.TAG,
"onMapLongClick == " + point.latitude + "," + point.longitude);
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(point).radius(GEOFENCE_RADIUS).strokeColor(
android.graphics.Color.BLUE).strokeWidth(2);
Circle circle = mMap.addCircle(circleOptions);
String key = Integer.toString(id);
id++;
mGeoFences.put(key, circle);
addGeoFences();
}
// Creates Geofence objects from all circles on the map and calls addGeofences API.
private void addGeoFences() {
List<Geofence> list = new ArrayList<Geofence>();
for (Map.Entry<String, Circle> entry : mGeoFences.entrySet()) {
Circle circle = entry.getValue();
Log.v(LocationActivity.TAG, "points == " +
circle.getCenter().latitude + "," +
circle.getCenter().longitude);
Geofence geofence = new Geofence.Builder()
.setRequestId(entry.getKey())
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(circle.getCenter().latitude,
circle.getCenter().longitude,
(float) circle.getRadius())
.setExpirationDuration(Geofence.NEVER_EXPIRE).build();
list.add(geofence);
}
if (list.isEmpty()) {
return;
}
// Clear off all the currently triggering geo_fences before new fences
// are added.
for (Circle triggeringGeoFence : mTriggeringFences.values()) {
triggeringGeoFence.remove();
}
mTriggeringFences.clear();
Log.v(LocationActivity.TAG, "addingGeoFences size = " + list.size());
mLocationClient.addGeofences(list, getPendingIntent(), this);
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(ACTION_GEOFENCE);
intent.setComponent(new ComponentName(LocationActivity.this,
GeoFenceIntentReceiver.class));
return PendingIntent.getBroadcast(LocationActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
private void removeGeoFences() {
List<String> requestIdsForRemoval = new ArrayList<String>();
if (mGeoFences.isEmpty()) return;
for (Map.Entry<String, Circle> entry : mGeoFences.entrySet()) {
String requestId = entry.getKey();
Circle circle = entry.getValue();
if (circle != null) {
circle.remove();
id --;
Log.v(LocationActivity.TAG, "RemoveGeoFence requestId == " + requestId);
Circle triggeringCircle = mTriggeringFences.get(requestId);
if (triggeringCircle != null) {
triggeringCircle.remove();
}
requestIdsForRemoval.add(requestId);
}
}
mGeoFences.clear();
mTriggeringFences.clear();
mLocationClient.removeGeofences(requestIdsForRemoval, this);
}
#Override
public void onAddGeofencesResult(int statusCode,
String[] geofenceRequestIds) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < geofenceRequestIds.length - 1; ++i) {
builder.append(geofenceRequestIds[i]);
builder.append(",");
}
builder.append(geofenceRequestIds[geofenceRequestIds.length - 1]);
Log.v(LocationActivity.TAG, "Added Geofences == "
+ statusCodeToString(statusCode) + " " + builder.toString());
mGeoFenceStatus.setText("Added Geofences "
+ statusCodeToString(statusCode) + " " + builder.toString());
}
private String statusCodeToString(int statusCode) {
switch(statusCode) {
case LocationStatusCodes.SUCCESS :
return "SUCCESS";
case LocationStatusCodes.GEOFENCE_NOT_AVAILABLE :
return "GEOFENCE_NOT_AVAILABLE";
case LocationStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES :
return "GEOFENCE_TOO_MANY_GEOFENCES";
case LocationStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS :
return "GEOFENCE_TOO_MANY_PENDING_INTENTS";
case LocationStatusCodes.ERROR :
return "ERROR";
}
return "UNKNOWN";
}
#Override
public void onRemoveGeofencesByPendingIntentResult(int statusCode, PendingIntent pendingIntent) {
// Do nothing
}
#Override
public void onRemoveGeofencesByRequestIdsResult(int statusCode,
String[] geofenceRequestIds) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < geofenceRequestIds.length - 1; ++i) {
builder.append(geofenceRequestIds[i]);
builder.append(",");
}
builder.append(geofenceRequestIds[geofenceRequestIds.length - 1]);
Log.v(LocationActivity.TAG, "Removed Geofence " +
statusCodeToString(statusCode) + " " + builder.toString());
mGeoFenceStatus.setText("Removed Geofences request_ids = " +
builder.toString() + " " + statusCodeToString(statusCode));
}
};
// Triggered when startAcitivity method is called in GeoFenceIntentReceiver.
// Updates UI as geofences are entered/exited.
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
boolean receiverStarted =
intent.getBooleanExtra("RECEIVER_STARTED", false);
if (!receiverStarted) {
return;
}
Bundle bundle = intent.getParcelableExtra("geo_fences");
ArrayList<String> requestIds =
bundle.getStringArrayList("request_ids");
if (requestIds == null) {
Log.v(LocationActivity.TAG, "request_ids == null");
return;
}
int transition = intent.getIntExtra("transition", -2);
for (String requestId : requestIds) {
Log.v(LocationActivity.TAG, "Triggering Geo Fence requestId "
+ requestId);
if (transition == Geofence.GEOFENCE_TRANSITION_ENTER) {
Circle circle = mGeoFences.get(requestId);
if (circle == null) {
continue;
}
Log.v(LocationActivity.TAG, "triggering_geo_fences enter == "
+ requestId);
// Add a superimposed red circle when a geofence is entered and
// put the corresponding object in triggering_fences.
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(circle.getCenter())
.radius(circle.getRadius())
.fillColor(Color.argb(100,100, 0, 0));
Circle newCircle = mMap.addCircle(circleOptions);
mTriggeringFences.put(requestId, newCircle);
} else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
Log.v(LocationActivity.TAG, "triggering_geo_fences exit == "
+ requestId);
Circle circle = mTriggeringFences.get(requestId);
if (circle == null) {
continue;
}
// Remove the superimposed red circle from the map and the
// corresponding Circle object from triggering_fences hash_map.
circle.remove();
mTriggeringFences.remove(requestId);
}
}
return;
}
}
2nd class
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
public ActivityRecognitionIntentService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent.getAction() != LocationActivity.ACTION_ACTIVITY_RECOGNITION) {
return;
}
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult
.extractResult(intent);
DetectedActivity detectedActivity = result
.getMostProbableActivity();
int activityType = detectedActivity.getType();
Log.v(LocationActivity.TAG, "activity_type == " + activityType);
// Put the activity_type as an intent extra and send a broadcast.
Intent send_intent = new Intent(
LocationActivity.ACTION_ACTIVITY_RECOGNITION);
send_intent.putExtra("activity_type", activityType);
sendBroadcast(send_intent);
}
}
}
edited add the main part of the code
Please Modify your restartLocationClient() Method like this:
private void restartLocationClient() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, mLocationCallback, mLocationCallback);
Log.v(LocationActivity.TAG, "Location Client connect");
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting()))
{
mLocationClient.connect(); // Somehow it becomes connected here
return;
}
}
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
It seems that your mLocationClient is null in this Method.
I hope this helps.
I know it's pretty late for this answer.
But for future reference, I'll post it anyways.
Basically, we have to understand the onConnect() method better. I find the explanation in this thread to be useful.
From there the workaround for this issue is pretty much straightforward.
Solution: restartLocationClient() is only called when mLocationClient.isConnected() returns true.
So, in your onResume method should look like the following:
if (mLocationClient.isConnected()) {
restartLocationClient();
}
Now it will work.

Categories