Example usage for android.content Context VIBRATOR_SERVICE

List of usage examples for android.content Context VIBRATOR_SERVICE

Introduction

In this page you can find the example usage for android.content Context VIBRATOR_SERVICE.

Prototype

String VIBRATOR_SERVICE

To view the source code for android.content Context VIBRATOR_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.os.Vibrator for interacting with the vibration hardware.

Usage

From source file:com.b44t.ui.PasscodeActivity.java

private void onPasscodeError() {
    if (getParentActivity() == null) {
        return;/*from w  ww.  java2s  .  co  m*/
    }
    Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
    if (v != null) {
        v.vibrate(200);
    }
    AndroidUtilities.shakeView(titleTextView, 2, 0);
}

From source file:com.sean.takeastand.alarmprocess.AlarmService.java

private void updateNotification() {
    /*if (!bRepeatingAlarmStepCheck) {
    mNotifTimePassed++;//  w  ww  .ja  v  a 2s . c  o  m
    }
    Log.i(TAG, "time since first notification: " + mNotifTimePassed + setMinutes(mNotifTimePassed));*/
    NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    PendingIntent[] pendingIntents = makeNotificationIntents();
    RemoteViews rvRibbon = new RemoteViews(getPackageName(), R.layout.stand_notification);
    rvRibbon.setOnClickPendingIntent(R.id.btnStood, pendingIntents[1]);
    rvRibbon.setTextViewText(R.id.notificationTimeStamp, notificationClockTime);
    /*rvRibbon.setTextViewText(R.id.stand_up_minutes, mNotifTimePassed +
        setMinutes(mNotifTimePassed));
    rvRibbon.setTextViewText(R.id.topTextView, getString(R.string.stand_up_time_up));*/
    NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(this);
    alarmNotificationBuilder.setContent(rvRibbon);
    alarmNotificationBuilder.setContentIntent(pendingIntents[0]).setAutoCancel(false)
            .setTicker(getString(R.string.stand_up_time_low)).setSmallIcon(R.drawable.ic_notification_small)
            .setContentTitle("Take A Stand ")
            //.setContentText("Mark Stood\n" + mNotifTimePassed + setMinutes(mNotifTimePassed))
            .extend(new NotificationCompat.WearableExtender().addAction(
                    new NotificationCompat.Action.Builder(R.drawable.ic_action_done, "Stood", pendingIntents[1])
                            .build())
                    .setContentAction(0).setHintHideIcon(true)
    //                    .setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.alarm_schedule_passed))
    );

    boolean[] alertType;
    if (mCurrentAlarmSchedule != null) {
        alertType = mCurrentAlarmSchedule.getAlertType();
    } else {
        alertType = Utils.getDefaultAlertType(this);
    }

    if ((alertType[0])) {
        alarmNotificationBuilder.setLights(238154000, 1000, 4000);
    }
    if (Utils.getRepeatAlerts(this)) {
        if (alertType[1]) {
            boolean bUseLastStepCounters = false;
            if (!bRepeatingAlarmStepCheck) {
                bRepeatingAlarmStepCheck = true;
                bUseLastStepCounters = UseLastStepCounters(null);
            }
            if (!bUseLastStepCounters) {
                bRepeatingAlarmStepCheck = false;
                alarmNotificationBuilder.setVibrate(mVibrationPattern);
                AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                if (audioManager.getMode() == AudioManager.RINGER_MODE_SILENT
                        && Utils.getVibrateOverride(this)) {
                    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                    v.vibrate(mVibrationPattern, -1);
                }
            }
        }
        if (alertType[2]) {
            Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            alarmNotificationBuilder.setSound(soundUri);
        }
    }

    Notification alarmNotification = alarmNotificationBuilder.build();
    notificationManager.notify(R.integer.AlarmNotificationID, alarmNotification);
}

From source file:org.mdc.chess.MDChess.java

private void initUI() {
    leftHanded = leftHandedView();//from  ww  w.j a va2s  .c o  m
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.main_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_main);
    navigationView.setNavigationItemSelectedListener(this);

    // title lines need to be regenerated every time due to layout changes (rotations)
    View firstTitleLine = findViewById(R.id.title_line);
    whiteTitleText = (TextView) findViewById(R.id.txt_first);
    whiteTitleText.setSelected(true);
    blackTitleText = (TextView) findViewById(R.id.txt_third);
    blackTitleText.setSelected(true);
    engineTitleText = (TextView) findViewById(R.id.txt_second);

    whiteFigText = (TextView) findViewById(R.id.white_pieces);
    whiteFigText.setTypeface(figNotation);
    whiteFigText.setSelected(true);
    whiteFigText.setTextColor(whiteTitleText.getTextColors());
    blackFigText = (TextView) findViewById(R.id.black_pieces);
    blackFigText.setTypeface(figNotation);
    blackFigText.setSelected(true);
    blackFigText.setTextColor(blackTitleText.getTextColors());

    status = (TextView) findViewById(R.id.status);
    moveListScroll = (ScrollView) findViewById(R.id.scrollView);
    moveList = (MoveListView) findViewById(R.id.moveList);
    thinking = (TextView) findViewById(R.id.thinking);
    defaultThinkingListTypeFace = thinking.getTypeface();
    status.setFocusable(false);
    moveListScroll.setFocusable(false);
    moveList.setFocusable(false);
    thinking.setFocusable(false);

    class ClickListener implements OnClickListener, OnTouchListener {
        // --Commented out by Inspection (31/10/2016 10:41 PM):private float touchX = -1;

        @Override
        public void onClick(View v) {
            //boolean left = touchX <= v.getWidth() / 2.0;
            //drawerLayout.openDrawer(left ? GravityCompat.START : GravityCompat.END);
            //touchX = -1;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //touchX = event.getX();
            return false;
        }
    }

    ClickListener listener = new ClickListener();
    firstTitleLine.setOnClickListener(listener);
    firstTitleLine.setOnTouchListener(listener);

    cb = (ChessBoardPlay) findViewById(R.id.chessboard);
    cb.setFocusable(true);
    cb.requestFocus();
    cb.setClickable(true);
    cb.setPgnOptions(pgnOptions);

    cb.setOnTouchListener(new OnTouchListener() {
        private final Handler handler = new Handler();
        private boolean pending = false;
        private final Runnable runnable = new Runnable() {
            public void run() {
                pending = false;
                handler.removeCallbacks(runnable);
                ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(20);
                boardMenuDialog();
            }
        };
        private boolean pendingClick = false;
        private int sq0 = -1;
        private float scrollX = 0;
        private float scrollY = 0;
        private float prevX = 0;
        private float prevY = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = MotionEventCompat.getActionMasked(event);
            switch (action) {
            case MotionEvent.ACTION_DOWN:
                handler.postDelayed(runnable, ViewConfiguration.getLongPressTimeout());
                pending = true;
                pendingClick = true;
                sq0 = cb.eventToSquare(event);
                scrollX = 0;
                scrollY = 0;
                prevX = event.getX();
                prevY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (pending) {
                    int sq = cb.eventToSquare(event);
                    if (sq != sq0) {
                        handler.removeCallbacks(runnable);
                        pendingClick = false;
                    }
                    float currX = event.getX();
                    float currY = event.getY();
                    if (onScroll(currX - prevX, currY - prevY)) {
                        handler.removeCallbacks(runnable);
                        pendingClick = false;
                    }
                    prevX = currX;
                    prevY = currY;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (pending) {
                    pending = false;
                    handler.removeCallbacks(runnable);
                    if (!pendingClick) {
                        break;
                    }
                    int sq = cb.eventToSquare(event);
                    if (sq == sq0) {
                        if (ctrl.humansTurn()) {
                            Move m = cb.mousePressed(sq);
                            if (m != null) {
                                setAutoMode(AutoMode.OFF);
                                ctrl.makeHumanMove(m);
                            }
                            setEgtbHints(cb.getSelectedSquare());
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                pending = false;
                handler.removeCallbacks(runnable);
                break;
            }
            return true;
        }

        private boolean onScroll(float distanceX, float distanceY) {
            if (invertScrollDirection) {
                distanceX = -distanceX;
                distanceY = -distanceY;
            }
            if ((scrollSensitivity > 0) && (cb.sqSize > 0)) {
                scrollX += distanceX;
                scrollY += distanceY;
                final float scrollUnit = cb.sqSize * scrollSensitivity;
                if (Math.abs(scrollX) >= Math.abs(scrollY)) {
                    // Undo/redo
                    int nRedo = 0, nUndo = 0;
                    while (scrollX > scrollUnit) {
                        nRedo++;
                        scrollX -= scrollUnit;
                    }
                    while (scrollX < -scrollUnit) {
                        nUndo++;
                        scrollX += scrollUnit;
                    }
                    if (nUndo + nRedo > 0) {
                        scrollY = 0;
                        setAutoMode(AutoMode.OFF);
                    }
                    if (nRedo + nUndo > 1) {
                        boolean analysis = gameMode.analysisMode();
                        boolean human = gameMode.playerWhite() || gameMode.playerBlack();
                        if (analysis || !human) {
                            ctrl.setGameMode(new GameMode(GameMode.TWO_PLAYERS));
                        }
                    }
                    for (int i = 0; i < nRedo; i++)
                        ctrl.redoMove();
                    for (int i = 0; i < nUndo; i++)
                        ctrl.undoMove();
                    ctrl.setGameMode(gameMode);
                    return nRedo + nUndo > 0;
                } else {
                    // Next/previous variation
                    int varDelta = 0;
                    while (scrollY > scrollUnit) {
                        varDelta++;
                        scrollY -= scrollUnit;
                    }
                    while (scrollY < -scrollUnit) {
                        varDelta--;
                        scrollY += scrollUnit;
                    }
                    if (varDelta != 0) {
                        scrollX = 0;
                        setAutoMode(AutoMode.OFF);
                        ctrl.changeVariation(varDelta);
                    }
                    return varDelta != 0;
                }
            }
            return false;
        }
    });
    /*cb.setOnTrackballListener(new ChessBoard.OnTrackballListener() {
            
    public void onTrackballEvent(MotionEvent event) {
        if (ctrl.humansTurn()) {
            Move m = cb.handleTrackballEvent(event);
            if (m != null) {
                setAutoMode(AutoMode.OFF);
                ctrl.makeHumanMove(m);
            }
            setEgtbHints(cb.getSelectedSquare());
        }
    }
            
    });*/

    moveList.setOnLongClickListener(new OnLongClickListener() {
        public boolean onLongClick(View v) {
            moveListMenuDialog();
            return true;
        }
    });
    thinking.setOnLongClickListener(new OnLongClickListener() {
        public boolean onLongClick(View v) {
            if (mShowThinking || gameMode.analysisMode()) {
                if (!pvMoves.isEmpty()) {
                    thinkingMenuDialog();
                }
            }
            return true;
        }
    });

}

From source file:org.rebo.app.TileMap.java

@Override
public boolean longPressHelper(final GeoPoint p1, final GeoPoint p2) {
    if (Build.VERSION.SDK_INT >= 26) {
        ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(50, 100));
    } else {//from   www .  ja va2 s . co  m
        ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(50);
    }
    //        showToastOnUiThread("Distance Touch!");
    App.routeSearch.showRoute(p1, p2);
    return true;
}

From source file:foam.mongoose.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {// w w w  . java  2s .  c  o  m

        String type = arr.getString(0);
        final Integer id = arr.getInt(1);
        String token = arr.getString(2);

        //Log.i("starwisp", "Update: "+type+" "+id+" "+token);

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            msg.show();
            return;
        }

        if (token.equals("play-sound")) {
            String name = arr.getString(3);

            if (name.equals("ping")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.ping);
                mp.start();
            }
            if (name.equals("active")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.active);
                mp.start();
            }
        }

        if (token.equals("vibrate")) {
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(arr.getInt(3));
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            //ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("gps-start")) {
            final String name = arr.getString(3);

            if (m_LocationManager == null) {
                m_LocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
                m_GPS = new DorisLocationListener(m_LocationManager);
            }

            m_GPS.Start((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            final String name = arr.getString(3);
            final String ssid = arr.getString(5);
            m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("http-request")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", name);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", filename);
            }
            return;
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {

            final String name = arr.getString(3);
            final String msg = arr.getString(5);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        // problem associating the id number
        if (id == 0)
            return;

        // now try and find the widget
        View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            vv.setEnabled(arr.getInt(3) == 1);
            return;
        }

        // special cases
        if (type.equals("linear-layout")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final int count = buttons.length();
                int vertcount = 0;
                LinearLayout vert = null;

                for (int i = 0; i < count; i++) {
                    JSONArray button = buttons.getJSONArray(i);

                    if (vertcount == 0) {
                        vert = new LinearLayout(ctx);
                        vert.setId(0);
                        vert.setOrientation(LinearLayout.VERTICAL);
                        horiz.addView(vert);
                    }
                    vertcount = (vertcount + 1) % height;

                    if (buttontype.equals("button")) {
                        Button b = new Button(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("toggle")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                String arg = "#f";
                                if (((ToggleButton) v).isChecked())
                                    arg = "#t";
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("single")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                final JSONArray items = arr.getJSONArray(3);
                v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {
                    @Override
                    public int getCount() {
                        return items.length();
                    }

                    @Override
                    public Fragment getItem(int position) {
                        try {
                            String fragname = items.getString(position);
                            return ActivityManager.GetFragment(fragname);
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                        return null;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                Bitmap bitmap = BitmapFactory.decodeFile(arr.getString(3));
                v.setImageBitmap(bitmap);
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            if (token.equals("request-focus")) {
                v.requestFocus();
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = (StarwispCanvas) vv;
            if (token.equals("drawlist")) {
                v.SetDrawList(arr.getJSONArray(3));
            }
            return;
        }

        if (type.equals("camera-preview")) {
            final CameraPreview v = (CameraPreview) vv;

            if (token.equals("take-picture")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path + datetime + ".jpg";
                        SaveData(filename, data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
            }

            if (token.equals("shutdown")) {
                v.Shutdown();
            }

            return;
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = arr.getJSONArray(3);
                ArrayList<String> spinnerArray = new ArrayList<String>();

                for (int i = 0; i < items.length(); i++) {
                    spinnerArray.add(items.getString(i));
                }

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx,
                        android.R.layout.simple_spinner_item, spinnerArray) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View v = super.getView(position, convertView, parent);
                        ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                        return v;
                    }
                };

                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                        try {
                            CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                    }

                    public void onNothingSelected(AdapterView<?> v) {
                    }
                });

            }
            return;
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing data " + e.toString());
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void notifyUserOfProximityAlert() {
    Handler mainHandler = new Handler(getActivity().getMainLooper());

    Runnable myRunnable = new Runnable() {
        @Override//from w ww  . ja v  a2  s. co m
        public void run() {
            final Dialog dialog = dialogInterface.getDialog(getActivity(),
                    R.layout.dialog_proximity_alert_warning, R.string.proximity_alert_warning);

            Button okButton = (Button) dialog.findViewById(R.id.proximity_alert_warning_ok_button);
            Button showOnMapButton = (Button) dialog
                    .findViewById(R.id.proximity_alert_warning_show_on_map_button);
            Button dismissAlertButton = (Button) dialog
                    .findViewById(R.id.proximity_alert_warning_dismiss_button);

            long[] pattern = { 0, 500, 200, 200, 300, 200, 200 };

            vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(pattern, 0);

            mediaPlayer = MediaPlayer.create(getActivity(), R.raw.proximity_warning_sound);

            if (mediaPlayer == null) {
                return;
            }

            mediaPlayer.setLooping(true);
            mediaPlayer.start();

            okButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alarmFiring = false;
                    vibrator.cancel();
                    vibrator = null;
                    proximityAlertWatcher.cancel(true);
                    proximityAlertWatcher = null;
                    mediaPlayer.stop();
                    mediaPlayer.release();

                    dialog.dismiss();
                    runScheduledAlarm(getResources().getInteger(R.integer.sixty),
                            getResources().getInteger(R.integer.proximity_alert_interval_time_seconds));
                }
            });

            showOnMapButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alarmFiring = false;
                    vibrator.cancel();
                    vibrator = null;
                    proximityAlertWatcher.cancel(true);
                    proximityAlertWatcher = null;
                    mediaPlayer.stop();
                    mediaPlayer.release();

                    browser.loadUrl("javascript:zoomToUserPosition()");

                    dialog.dismiss();
                    runScheduledAlarm(getResources().getInteger(R.integer.sixty),
                            getResources().getInteger(R.integer.proximity_alert_interval_time_seconds));

                }
            });

            dismissAlertButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alarmFiring = false;
                    vibrator.cancel();
                    vibrator = null;
                    proximityAlertWatcher.cancel(true);
                    proximityAlertWatcher = null;
                    mediaPlayer.stop();
                    mediaPlayer.release();

                    dialog.dismiss();
                }
            });

            dialog.show();
        } // This is your code
    };
    mainHandler.post(myRunnable);
}

From source file:paulscode.android.mupen64plusae.game.GameFragment.java

@SuppressLint("InlinedApi")
private void initControllers(View inputSource) {
    // By default, send Player 1 rumbles through phone vibrator
    final Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
    mCoreFragment.registerVibrator(1, vibrator);

    // Create the touchscreen controls
    if (mGamePrefs.isTouchscreenEnabled) {
        if (!mGamePrefs.sensorAxisX.isEmpty() || !mGamePrefs.sensorAxisY.isEmpty()) {
            // Create the sensor controller
            final SensorManager sensorManager = (SensorManager) getActivity()
                    .getSystemService(Context.SENSOR_SERVICE);
            mSensorController = new SensorController(mCoreFragment, sensorManager, mOverlay,
                    mGamePrefs.sensorAxisX, mGamePrefs.sensorSensitivityX, mGamePrefs.sensorAngleX,
                    mGamePrefs.sensorAxisY, mGamePrefs.sensorSensitivityY, mGamePrefs.sensorAngleY);
            if (mGamePrefs.sensorActivateOnStart) {
                mSensorController.setSensorEnabled(true);
                mOverlay.onSensorEnabled(true);
            }// ww w .jav  a2s .c  o m
        }

        // Create the touchscreen controller
        mTouchscreenController = new TouchController(mCoreFragment, mTouchscreenMap, mOverlay, vibrator,
                mGamePrefs.touchscreenAutoHold, mGlobalPrefs.isTouchscreenFeedbackEnabled,
                mGamePrefs.touchscreenNotAutoHoldables, mSensorController, mGamePrefs.invertTouchXAxis,
                mGamePrefs.invertTouchYAxis);
        inputSource.setOnTouchListener(this);
        mDrawerLayout.setTouchMap(mTouchscreenMap);
    }

    //Check for controller configuration
    boolean needs1 = false;
    boolean needs2 = false;
    boolean needs3 = false;
    boolean needs4 = false;

    // Popup the multi-player dialog if necessary and abort if any players are unassigned
    final RomDatabase romDatabase = RomDatabase.getInstance();

    if (!romDatabase.hasDatabaseFile()) {
        romDatabase.setDatabaseFile(mAppData.mupen64plus_ini);
    }

    final RomDetail romDetail = romDatabase.lookupByMd5WithFallback(mRomMd5, new File(mRomPath), mRomCrc);
    if (romDetail.players > 1 && mGamePrefs.playerMap.isEnabled() && mGlobalPrefs.getPlayerMapReminder()) {
        mGamePrefs.playerMap.removeUnavailableMappings();
        needs1 = mGamePrefs.isControllerEnabled1 && !mGamePrefs.playerMap.isMapped(1);
        needs2 = mGamePrefs.isControllerEnabled2 && !mGamePrefs.playerMap.isMapped(2);
        needs3 = mGamePrefs.isControllerEnabled3 && !mGamePrefs.playerMap.isMapped(3) && romDetail.players > 2;
        needs4 = mGamePrefs.isControllerEnabled4 && !mGamePrefs.playerMap.isMapped(4) && romDetail.players > 3;

        if (needs1 || needs2 || needs3 || needs4) {
            Popups.showNeedsPlayerMap(getActivity());
        }
    }

    // Create the input providers shared among all peripheral controllers
    mKeyProvider = new KeyProvider(inputSource, ImeFormula.DEFAULT, mGlobalPrefs.unmappableKeyCodes);
    final MogaProvider mogaProvider = new MogaProvider(mMogaController);
    mAxisProvider = new AxisProvider();

    // Request focus for proper listening
    inputSource.requestFocus();
    // Create the peripheral controls to handle key/stick presses
    if (mGamePrefs.isControllerEnabled1 && !needs1) {
        final ControllerProfile p = mGamePrefs.controllerProfile1;
        new PeripheralController(mCoreFragment, 1, mGamePrefs.playerMap, p.getMap(), p.getDeadzone(),
                p.getSensitivityX(), p.getSensitivityY(), mOverlay, this, mSensorController, mKeyProvider,
                mAxisProvider, mogaProvider);
        Log.i("GameFragment", "Player 1 has been enabled");
    }
    if (mGamePrefs.isControllerEnabled2 && !needs2) {
        final ControllerProfile p = mGamePrefs.controllerProfile2;
        new PeripheralController(mCoreFragment, 2, mGamePrefs.playerMap, p.getMap(), p.getDeadzone(),
                p.getSensitivityX(), p.getSensitivityY(), mOverlay, this, null, mKeyProvider, mAxisProvider,
                mogaProvider);
        Log.i("GameFragment", "Player 2 has been enabled");
    }
    if (mGamePrefs.isControllerEnabled3 && !needs3) {
        final ControllerProfile p = mGamePrefs.controllerProfile3;
        new PeripheralController(mCoreFragment, 3, mGamePrefs.playerMap, p.getMap(), p.getDeadzone(),
                p.getSensitivityX(), p.getSensitivityY(), mOverlay, this, null, mKeyProvider, mAxisProvider,
                mogaProvider);
        Log.i("GameFragment", "Player 3 has been enabled");
    }
    if (mGamePrefs.isControllerEnabled4 && !needs4) {
        final ControllerProfile p = mGamePrefs.controllerProfile4;
        new PeripheralController(mCoreFragment, 4, mGamePrefs.playerMap, p.getMap(), p.getDeadzone(),
                p.getSensitivityX(), p.getSensitivityY(), mOverlay, this, null, mKeyProvider, mAxisProvider,
                mogaProvider);
        Log.i("GameFragment", "Player 4 has been enabled");
    }
}

From source file:org.petero.droidfish.DroidFish.java

private final void initUI() {
    leftHanded = leftHandedView();//from ww w  .  j  a v  a  2s. co m
    setContentView(leftHanded ? R.layout.main_left_handed : R.layout.main);
    Util.overrideFonts(findViewById(android.R.id.content));

    // title lines need to be regenerated every time due to layout changes (rotations)
    firstTitleLine = findViewById(R.id.first_title_line);
    secondTitleLine = findViewById(R.id.second_title_line);
    whiteTitleText = (TextView) findViewById(R.id.white_clock);
    whiteTitleText.setSelected(true);
    blackTitleText = (TextView) findViewById(R.id.black_clock);
    blackTitleText.setSelected(true);
    engineTitleText = (TextView) findViewById(R.id.title_text);
    whiteFigText = (TextView) findViewById(R.id.white_pieces);
    whiteFigText.setTypeface(figNotation);
    whiteFigText.setSelected(true);
    whiteFigText.setTextColor(whiteTitleText.getTextColors());
    blackFigText = (TextView) findViewById(R.id.black_pieces);
    blackFigText.setTypeface(figNotation);
    blackFigText.setSelected(true);
    blackFigText.setTextColor(blackTitleText.getTextColors());
    summaryTitleText = (TextView) findViewById(R.id.title_text_summary);

    status = (TextView) findViewById(R.id.status);
    moveListScroll = (ScrollView) findViewById(R.id.scrollView);
    moveList = (TextView) findViewById(R.id.moveList);
    defaultMoveListTypeFace = moveList.getTypeface();
    thinking = (TextView) findViewById(R.id.thinking);
    defaultThinkingListTypeFace = thinking.getTypeface();
    status.setFocusable(false);
    moveListScroll.setFocusable(false);
    moveList.setFocusable(false);
    moveList.setMovementMethod(LinkMovementMethod.getInstance());
    thinking.setFocusable(false);

    firstTitleLine.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            openOptionsMenu();
        }
    });
    secondTitleLine.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            openOptionsMenu();
        }
    });

    cb = (ChessBoardPlay) findViewById(R.id.chessboard);
    cb.setFocusable(true);
    cb.requestFocus();
    cb.setClickable(true);
    cb.setPgnOptions(pgnOptions);

    cb.setOnTouchListener(new OnTouchListener() {
        private boolean pending = false;
        private boolean pendingClick = false;
        private int sq0 = -1;
        private float scrollX = 0;
        private float scrollY = 0;
        private float prevX = 0;
        private float prevY = 0;
        private Handler handler = new Handler();
        private Runnable runnable = new Runnable() {
            public void run() {
                pending = false;
                handler.removeCallbacks(runnable);
                ((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(20);
                removeDialog(BOARD_MENU_DIALOG);
                showDialog(BOARD_MENU_DIALOG);
            }
        };

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = MotionEventCompat.getActionMasked(event);
            switch (action) {
            case MotionEvent.ACTION_DOWN:
                handler.postDelayed(runnable, ViewConfiguration.getLongPressTimeout());
                pending = true;
                pendingClick = true;
                sq0 = cb.eventToSquare(event);
                scrollX = 0;
                scrollY = 0;
                prevX = event.getX();
                prevY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (pending) {
                    int sq = cb.eventToSquare(event);
                    if (sq != sq0) {
                        handler.removeCallbacks(runnable);
                        pendingClick = false;
                    }
                    float currX = event.getX();
                    float currY = event.getY();
                    if (onScroll(currX - prevX, currY - prevY)) {
                        handler.removeCallbacks(runnable);
                        pendingClick = false;
                    }
                    prevX = currX;
                    prevY = currY;
                }
                break;
            case MotionEvent.ACTION_UP:
                if (pending) {
                    pending = false;
                    handler.removeCallbacks(runnable);
                    if (!pendingClick)
                        break;
                    int sq = cb.eventToSquare(event);
                    if (sq == sq0) {
                        if (ctrl.humansTurn()) {
                            Move m = cb.mousePressed(sq);
                            if (m != null) {
                                setAutoMode(AutoMode.OFF);
                                ctrl.makeHumanMove(m);
                            }
                            setEgtbHints(cb.getSelectedSquare());
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                pending = false;
                handler.removeCallbacks(runnable);
                break;
            }
            return true;
        }

        private boolean onScroll(float distanceX, float distanceY) {
            if (invertScrollDirection) {
                distanceX = -distanceX;
                distanceY = -distanceY;
            }
            if ((scrollSensitivity > 0) && (cb.sqSize > 0)) {
                scrollX += distanceX;
                scrollY += distanceY;
                final float scrollUnit = cb.sqSize * scrollSensitivity;
                if (Math.abs(scrollX) >= Math.abs(scrollY)) {
                    // Undo/redo
                    int nRedo = 0, nUndo = 0;
                    while (scrollX > scrollUnit) {
                        nRedo++;
                        scrollX -= scrollUnit;
                    }
                    while (scrollX < -scrollUnit) {
                        nUndo++;
                        scrollX += scrollUnit;
                    }
                    if (nUndo + nRedo > 0) {
                        scrollY = 0;
                        setAutoMode(AutoMode.OFF);
                    }
                    if (nRedo + nUndo > 1) {
                        boolean analysis = gameMode.analysisMode();
                        boolean human = gameMode.playerWhite() || gameMode.playerBlack();
                        if (analysis || !human)
                            ctrl.setGameMode(new GameMode(GameMode.TWO_PLAYERS));
                    }
                    for (int i = 0; i < nRedo; i++)
                        ctrl.redoMove();
                    for (int i = 0; i < nUndo; i++)
                        ctrl.undoMove();
                    ctrl.setGameMode(gameMode);
                    return nRedo + nUndo > 0;
                } else {
                    // Next/previous variation
                    int varDelta = 0;
                    while (scrollY > scrollUnit) {
                        varDelta++;
                        scrollY -= scrollUnit;
                    }
                    while (scrollY < -scrollUnit) {
                        varDelta--;
                        scrollY += scrollUnit;
                    }
                    if (varDelta != 0) {
                        scrollX = 0;
                        setAutoMode(AutoMode.OFF);
                        ctrl.changeVariation(varDelta);
                    }
                    return varDelta != 0;
                }
            }
            return false;
        }
    });
    cb.setOnTrackballListener(new ChessBoard.OnTrackballListener() {
        public void onTrackballEvent(MotionEvent event) {
            if (ctrl.humansTurn()) {
                Move m = cb.handleTrackballEvent(event);
                if (m != null) {
                    setAutoMode(AutoMode.OFF);
                    ctrl.makeHumanMove(m);
                }
                setEgtbHints(cb.getSelectedSquare());
            }
        }
    });

    moveList.setOnLongClickListener(new OnLongClickListener() {
        public boolean onLongClick(View v) {
            removeDialog(MOVELIST_MENU_DIALOG);
            showDialog(MOVELIST_MENU_DIALOG);
            return true;
        }
    });
    thinking.setOnLongClickListener(new OnLongClickListener() {
        public boolean onLongClick(View v) {
            if (mShowThinking || gameMode.analysisMode()) {
                if (!pvMoves.isEmpty()) {
                    removeDialog(THINKING_MENU_DIALOG);
                    showDialog(THINKING_MENU_DIALOG);
                }
            }
            return true;
        }
    });

    custom1Button = (ImageButton) findViewById(R.id.custom1Button);
    custom1ButtonActions.setImageButton(custom1Button, this);
    custom2Button = (ImageButton) findViewById(R.id.custom2Button);
    custom2ButtonActions.setImageButton(custom2Button, this);
    custom3Button = (ImageButton) findViewById(R.id.custom3Button);
    custom3ButtonActions.setImageButton(custom3Button, this);

    modeButton = (ImageButton) findViewById(R.id.modeButton);
    modeButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(GAME_MODE_DIALOG);
        }
    });
    modeButton.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            openOptionsMenu();
            return true;
        }
    });
    undoButton = (ImageButton) findViewById(R.id.undoButton);
    undoButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setAutoMode(AutoMode.OFF);
            ctrl.undoMove();
        }
    });
    undoButton.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            removeDialog(GO_BACK_MENU_DIALOG);
            showDialog(GO_BACK_MENU_DIALOG);
            return true;
        }
    });
    redoButton = (ImageButton) findViewById(R.id.redoButton);
    redoButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setAutoMode(AutoMode.OFF);
            ctrl.redoMove();
        }
    });
    redoButton.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            removeDialog(GO_FORWARD_MENU_DIALOG);
            showDialog(GO_FORWARD_MENU_DIALOG);
            return true;
        }
    });
}

From source file:com.speedtong.example.ui.chatting.ChattingActivity.java

/**
 * //from  w  w  w.  ja  v  a2  s.com
 * @param milliseconds
 */
public synchronized void vibrate(long milliseconds) {
    Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    if (mVibrator == null) {
        return;
    }
    mVibrator.vibrate(milliseconds);
}

From source file:foam.opensauces.StarwispBuilder.java

public void Update(final StarwispActivity ctx, final String ctxname, JSONArray arr) {
    try {//from  w w  w.  j  av  a 2  s.  co  m

        String type = arr.getString(0);
        final Integer id = arr.getInt(1);
        String token = arr.getString(2);

        Log.i("starwisp", "Update: " + type + " " + id + " " + token);

        // non widget commands
        if (token.equals("toast")) {
            Toast msg = Toast.makeText(ctx.getBaseContext(), arr.getString(3), Toast.LENGTH_SHORT);
            msg.show();
            return;
        }

        if (token.equals("play-sound")) {
            String name = arr.getString(3);

            if (name.equals("ping")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.ping);
                mp.start();
            }
            if (name.equals("active")) {
                MediaPlayer mp = MediaPlayer.create(ctx, R.raw.active);
                mp.start();
            }
        }

        if (token.equals("vibrate")) {
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(arr.getInt(3));
        }

        if (type.equals("replace-fragment")) {
            int ID = arr.getInt(1);
            String name = arr.getString(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            FragmentTransaction ft = ctx.getSupportFragmentManager().beginTransaction();

            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            //ft.setCustomAnimations(
            //    R.animator.card_flip_right_in, R.animator.card_flip_right_out,
            //    R.animator.card_flip_left_in, R.animator.card_flip_left_out);
            ft.replace(ID, fragment);
            //ft.addToBackStack(null);
            ft.commit();
            return;
        }

        if (token.equals("dialog-fragment")) {
            FragmentManager fm = ctx.getSupportFragmentManager();
            final int ID = arr.getInt(3);
            final JSONArray lp = arr.getJSONArray(4);
            final String name = arr.getString(5);

            final Dialog dialog = new Dialog(ctx);
            dialog.setTitle("Title...");

            LinearLayout inner = new LinearLayout(ctx);
            inner.setId(ID);
            inner.setLayoutParams(BuildLayoutParams(lp));

            dialog.setContentView(inner);

            //                Fragment fragment = ActivityManager.GetFragment(name);
            //                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            //                fragmentTransaction.add(ID,fragment);
            //                fragmentTransaction.commit();

            dialog.show();

            /*                DialogFragment df = new DialogFragment() {
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                LinearLayout inner = new LinearLayout(ctx);
                inner.setId(ID);
                inner.setLayoutParams(BuildLayoutParams(lp));
                    
                return inner;
            }
                    
            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                Dialog ret = super.onCreateDialog(savedInstanceState);
                Log.i("starwisp","MAKINGDAMNFRAGMENT");
                    
                Fragment fragment = ActivityManager.GetFragment(name);
                FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(1,fragment);
                fragmentTransaction.commit();
                return ret;
            }
                            };
                            df.show(ctx.getFragmentManager(), "foo");
            */
        }

        if (token.equals("time-picker-dialog")) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            TimePickerDialog d = new TimePickerDialog(ctx, null, hour, minute, true);
            d.show();
            return;
        }
        ;

        if (token.equals("make-directory")) {
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(3));
            file.mkdirs();
            return;
        }

        if (token.equals("list-files")) {
            final String name = arr.getString(3);
            File file = new File(((StarwispActivity) ctx).m_AppDir + arr.getString(5));
            // todo, should probably call callback with empty list
            if (file != null) {
                File list[] = file.listFiles();

                if (list != null) {
                    String code = "(";
                    for (int i = 0; i < list.length; i++) {
                        code += " \"" + list[i].getName() + "\"";
                    }
                    code += ")";

                    DialogCallback(ctx, ctxname, name, code);
                }
            }
            return;
        }

        if (token.equals("gps-start")) {
            final String name = arr.getString(3);

            if (m_LocationManager == null) {
                m_LocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
                m_GPS = new DorisLocationListener(m_LocationManager);
            }

            m_GPS.Start((StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("walk-draggable")) {
            final String name = arr.getString(3);
            int iid = arr.getInt(5);
            DialogCallback(ctx, ctxname, name, WalkDraggable(ctx, name, ctxname, iid));
            return;
        }

        if (token.equals("delayed")) {
            final String name = arr.getString(3);
            final int d = arr.getInt(5);
            Runnable timerThread = new Runnable() {
                public void run() {
                    DialogCallback(ctx, ctxname, name, "");
                }
            };
            m_Handler.removeCallbacksAndMessages(null);
            m_Handler.postDelayed(timerThread, d);
            return;
        }

        if (token.equals("network-connect")) {
            final String name = arr.getString(3);
            final String ssid = arr.getString(5);
            m_NetworkManager.Start(ssid, (StarwispActivity) ctx, name, this);
            return;
        }

        if (token.equals("http-request")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http request");
                final String name = arr.getString(3);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "normal", name);
            }
            return;
        }

        if (token.equals("http-download")) {
            if (m_NetworkManager.state == NetworkManager.State.CONNECTED) {
                Log.i("starwisp", "attempting http dl request");
                final String filename = arr.getString(4);
                final String url = arr.getString(5);
                m_NetworkManager.StartRequestThread(url, "download", filename);
            }
            return;
        }

        if (token.equals("send-mail")) {
            final String to[] = new String[1];
            to[0] = arr.getString(3);
            final String subject = arr.getString(4);
            final String body = arr.getString(5);

            JSONArray attach = arr.getJSONArray(6);
            ArrayList<String> paths = new ArrayList<String>();
            for (int a = 0; a < attach.length(); a++) {
                Log.i("starwisp", attach.getString(a));
                paths.add(attach.getString(a));
            }

            email(ctx, to[0], "", subject, body, paths);
        }

        if (token.equals("date-picker-dialog")) {
            final Calendar c = Calendar.getInstance();
            int day = c.get(Calendar.DAY_OF_MONTH);
            int month = c.get(Calendar.MONTH);
            int year = c.get(Calendar.YEAR);

            final String name = arr.getString(3);

            // Create a new instance of TimePickerDialog and return it
            DatePickerDialog d = new DatePickerDialog(ctx, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    DialogCallback(ctx, ctxname, name, day + " " + month + " " + year);
                }
            }, year, month, day);
            d.show();
            return;
        }
        ;

        if (token.equals("alert-dialog")) {

            final String name = arr.getString(3);
            final String msg = arr.getString(5);

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int result = 0;
                    if (which == DialogInterface.BUTTON_POSITIVE)
                        result = 1;
                    DialogCallback(ctx, ctxname, name, "" + result);
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setMessage(msg).setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener).show();

            return;
        }

        if (token.equals("start-activity")) {
            ActivityManager.StartActivity(ctx, arr.getString(3), arr.getInt(4), arr.getString(5));
            return;
        }

        if (token.equals("start-activity-goto")) {
            ActivityManager.StartActivityGoto(ctx, arr.getString(3), arr.getString(4));
            return;
        }

        if (token.equals("finish-activity")) {
            ctx.setResult(arr.getInt(3));
            ctx.finish();
            return;
        }

        ///////////////////////////////////////////////////////////

        // now try and find the widget
        View vv = ctx.findViewById(id);
        if (vv == null) {
            Log.i("starwisp", "Can't find widget : " + id);
            return;
        }

        // tokens that work on everything
        if (token.equals("hide")) {
            vv.setVisibility(View.GONE);
            return;
        }

        if (token.equals("show")) {
            vv.setVisibility(View.VISIBLE);
            return;
        }

        // tokens that work on everything
        if (token.equals("set-enabled")) {
            vv.setEnabled(arr.getInt(3) == 1);
            return;
        }

        // special cases
        if (type.equals("linear-layout")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        // special cases
        if (type.equals("draggable")) {
            LinearLayout v = (LinearLayout) vv;
            if (token.equals("contents")) {
                //                    v.removeAllViews();
                JSONArray children = arr.getJSONArray(3);
                for (int i = 0; i < children.length(); i++) {
                    Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
                }
            }
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = (LinearLayout) vv;
            if (token.equals("grid-buttons")) {
                horiz.removeAllViews();

                JSONArray params = arr.getJSONArray(3);
                String buttontype = params.getString(0);
                int height = params.getInt(1);
                int textsize = params.getInt(2);
                LinearLayout.LayoutParams lp = BuildLayoutParams(params.getJSONArray(3));
                final JSONArray buttons = params.getJSONArray(4);
                final int count = buttons.length();
                int vertcount = 0;
                LinearLayout vert = null;

                for (int i = 0; i < count; i++) {
                    JSONArray button = buttons.getJSONArray(i);

                    if (vertcount == 0) {
                        vert = new LinearLayout(ctx);
                        vert.setId(0);
                        vert.setOrientation(LinearLayout.VERTICAL);
                        horiz.addView(vert);
                    }
                    vertcount = (vertcount + 1) % height;

                    if (buttontype.equals("button")) {
                        Button b = new Button(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("toggle")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                String arg = "#f";
                                if (((ToggleButton) v).isChecked())
                                    arg = "#t";
                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                            }
                        });
                        vert.addView(b);
                    } else if (buttontype.equals("single")) {
                        ToggleButton b = new ToggleButton(ctx);
                        b.setId(button.getInt(0));
                        b.setText(button.getString(1));
                        b.setTextSize(textsize);
                        b.setLayoutParams(lp);
                        b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                        final String fn = params.getString(5);
                        b.setOnClickListener(new View.OnClickListener() {
                            public void onClick(View v) {
                                try {
                                    for (int i = 0; i < count; i++) {
                                        JSONArray button = buttons.getJSONArray(i);
                                        int bid = button.getInt(0);
                                        if (bid != v.getId()) {
                                            ToggleButton tb = (ToggleButton) ctx.findViewById(bid);
                                            tb.setChecked(false);
                                        }
                                    }
                                } catch (JSONException e) {
                                    Log.e("starwisp", "Error parsing data " + e.toString());
                                }

                                CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                            }
                        });
                        vert.addView(b);
                    }

                }
            }
        }

        /*
                    if (type.equals("grid-layout")) {
        GridLayout v = (GridLayout)vv;
        if (token.equals("contents")) {
            v.removeAllViews();
            JSONArray children = arr.getJSONArray(3);
            for (int i=0; i<children.length(); i++) {
                Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
            }
        }
                    }
        */
        if (type.equals("view-pager")) {
            ViewPager v = (ViewPager) vv;
            if (token.equals("switch")) {
                v.setCurrentItem(arr.getInt(3));
            }
            if (token.equals("pages")) {
                final JSONArray items = arr.getJSONArray(3);
                v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {
                    @Override
                    public int getCount() {
                        return items.length();
                    }

                    @Override
                    public Fragment getItem(int position) {
                        try {
                            String fragname = items.getString(position);
                            return ActivityManager.GetFragment(fragname);
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                        return null;
                    }
                });
            }
        }

        if (type.equals("image-view")) {
            ImageView v = (ImageView) vv;
            if (token.equals("image")) {
                int iid = ctx.getResources().getIdentifier(arr.getString(3), "drawable", ctx.getPackageName());
                v.setImageResource(iid);
            }
            if (token.equals("external-image")) {
                Bitmap bitmap = BitmapFactory.decodeFile(arr.getString(3));
                v.setImageBitmap(bitmap);
            }
            return;
        }

        if (type.equals("text-view") || type.equals("debug-text-view")) {
            TextView v = (TextView) vv;
            if (token.equals("text")) {
                if (type.equals("debug-text-view")) {
                    //v.setMovementMethod(new ScrollingMovementMethod());
                }
                v.setText(arr.getString(3));
            }
            return;
        }

        if (type.equals("edit-text")) {
            EditText v = (EditText) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }
            if (token.equals("request-focus")) {
                v.requestFocus();
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
            }
            return;
        }

        if (type.equals("button")) {
            Button v = (Button) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = (ToggleButton) vv;
            if (token.equals("text")) {
                v.setText(arr.getString(3));
                return;
            }

            if (token.equals("checked")) {
                if (arr.getInt(3) == 0)
                    v.setChecked(false);
                else
                    v.setChecked(true);
                return;
            }

            if (token.equals("listener")) {
                final String fn = arr.getString(3);
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        m_Scheme.eval("(" + fn + ")");
                    }
                });
            }
            return;
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = (StarwispCanvas) vv;
            if (token.equals("drawlist")) {
                v.SetDrawList(arr.getJSONArray(3));
            }
            return;
        }

        if (type.equals("camera-preview")) {
            final CameraPreview v = (CameraPreview) vv;

            if (token.equals("take-picture")) {
                final String path = ((StarwispActivity) ctx).m_AppDir + arr.getString(3);

                v.TakePicture(new PictureCallback() {
                    public void onPictureTaken(byte[] data, Camera camera) {
                        String datetime = getDateTime();
                        String filename = path + datetime + ".jpg";
                        SaveData(filename, data);
                        v.Shutdown();
                        ctx.finish();
                    }
                });
            }

            if (token.equals("shutdown")) {
                v.Shutdown();
            }

            return;
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            if (token.equals("max")) {
                // android seekbar bug workaround
                int p = v.getProgress();
                v.setMax(0);
                v.setProgress(0);
                v.setMax(arr.getInt(3));
                v.setProgress(1000);

                // not working.... :(
            }
        }

        if (type.equals("spinner")) {
            Spinner v = (Spinner) vv;

            if (token.equals("selection")) {
                v.setSelection(arr.getInt(3));
            }

            if (token.equals("array")) {
                final JSONArray items = arr.getJSONArray(3);
                ArrayList<String> spinnerArray = new ArrayList<String>();

                for (int i = 0; i < items.length(); i++) {
                    spinnerArray.add(items.getString(i));
                }

                ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx,
                        android.R.layout.simple_spinner_item, spinnerArray) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View v = super.getView(position, convertView, parent);
                        ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                        return v;
                    }
                };

                v.setAdapter(spinnerArrayAdapter);

                final int wid = id;
                // need to update for new values
                v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                        try {
                            CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                        } catch (JSONException e) {
                            Log.e("starwisp", "Error parsing data " + e.toString());
                        }
                    }

                    public void onNothingSelected(AdapterView<?> v) {
                    }
                });

            }
            return;
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing data " + e.toString());
    }
}