0
votes

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.

1
Here is your error, 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) and it is self explanatory. - Raheel
I didn't understand the error. - user7364622

1 Answers

0
votes

The fix is to use:

drop = (LinearLayout) view.findViewById(R.id.bottomlinear);

instead of:

drop = (LinearLayout) findViewById(R.id.bottomlinear);