com.lumisky.bluetooth_led.Interface.Bulbs.BulbsActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.lumisky.bluetooth_led.Interface.Bulbs.BulbsActivity.java

Source

/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lumisky.bluetooth_led.Interface.Bulbs;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;

import com.lumisky.bluetooth_led.COMM.BLEPeripheralClient;
import com.lumisky.bluetooth_led.COMM.ConnectionManager;
import com.lumisky.bluetooth_led.COMM.LEDDeviceCMDMgr;
import com.lumisky.bluetooth_led.COMM.LedDeviceInfo;
import com.lumisky.bluetooth_led.Interface.CustomView.IOSSwitchButton;
import com.lumisky.bluetooth_led.Interface.CustomView.PagerSlidingTabStrip;
import com.lumisky.bluetooth_led.R;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

public class BulbsActivity extends FragmentActivity implements ColorFragment.OnColorFragmentInteraction,
        WhiteFragment.OnWhiteInteractionListener, EffectFragment.OnFragmentInteractionListener,
        MusicFragment.OnFragmentInteractionListener, AlarmFragment.OnFragmentInteractionListener, Observer {

    private final Handler handler = new Handler();

    private PagerSlidingTabStrip tabs;
    private ViewPager pager;
    private MyPagerAdapter adapter;
    private LedDeviceInfo led;
    private Drawable oldBackground = null;
    private int currentColor;
    private int[] colorList;
    private Fragment[] pages;
    private String[] deviceUniIDs;
    private Boolean flag;
    private int flag_time_out;
    private int r, g, b, w, power;
    private Boolean init;
    private IOSSwitchButton mSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bulbs);
        init = true;
        init();
        ArrayList<String> arrayList = getIntent().getStringArrayListExtra("DeviceUniIDs");
        deviceUniIDs = new String[arrayList.size()];
        deviceUniIDs = arrayList.toArray(deviceUniIDs);
        ((EffectFragment) pages[2]).setDeviceUniIDs(deviceUniIDs);

        ConnectionManager.GetCurrent().getBLEPeripheralClientUniID(deviceUniIDs[0]).addObserver(this);
        ConnectionManager.GetCurrent().SendDataByDeviceUniD(deviceUniIDs[0],
                LEDDeviceCMDMgr.getCommandDataForQuery());
        flag = true;
        flag_time_out = 100;
    }

    private void init() {
        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);
        adapter = new MyPagerAdapter(getSupportFragmentManager());

        pager.setAdapter(adapter);

        pages = new Fragment[] { new ColorFragment(), new WhiteFragment(), new EffectFragment(),
                new MusicFragment(), new AlarmFragment() };
        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
                getResources().getDisplayMetrics());
        pager.setPageMargin(pageMargin);

        tabs.setViewPager(pager);

        tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int i) {
                changeColor(colorList[i]);
            }

            @Override
            public void onPageScrolled(int i, float v, int i2) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        colorList = new int[] { getResources().getColor(R.color.flatDarkRed),
                getResources().getColor(R.color.flatDarkYellow), getResources().getColor(R.color.flatDarkTeal),
                getResources().getColor(R.color.flatDarkBlue), getResources().getColor(R.color.flatDarkPurple) };
        changeColor(colorList[0]);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bulbs_action, menu);
        mSwitch = (IOSSwitchButton) menu.findItem(R.id.power_switch).getActionView();
        mSwitch.setChecked(power == 0x23);
        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switchPowerClicked();
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

        }

        return super.onOptionsItemSelected(item);
    }

    private void switchPowerClicked() {

        ConnectionManager.GetCurrent().SendDataForPowerByDeviceUniDs(deviceUniIDs, mSwitch.isChecked());
    }

    private void changeColor(int newColor) {

        tabs.setIndicatorColor(newColor);

        // change ActionBar color just if an ActionBar is available
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

            Drawable colorDrawable = new ColorDrawable(newColor);
            Drawable bottomDrawable = getResources().getDrawable(R.drawable.actionbar_bottom);
            LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable, bottomDrawable });

            if (oldBackground == null) {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    ld.setCallback(drawableCallback);
                } else {
                    getActionBar().setBackgroundDrawable(ld);
                }

            } else {

                TransitionDrawable td = new TransitionDrawable(new Drawable[] { oldBackground, ld });

                // workaround for broken ActionBarContainer drawable handling on
                // pre-API 17 builds
                // https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    td.setCallback(drawableCallback);
                } else {
                    getActionBar().setBackgroundDrawable(td);
                }

                td.startTransition(200);

            }

            oldBackground = ld;

            getActionBar().setDisplayShowTitleEnabled(false);
            getActionBar().setDisplayShowTitleEnabled(true);

        }

        currentColor = newColor;

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentColor", currentColor);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        currentColor = savedInstanceState.getInt("currentColor");
        changeColor(currentColor);
    }

    private Drawable.Callback drawableCallback = new Drawable.Callback() {
        @Override
        public void invalidateDrawable(Drawable who) {
            getActionBar().setBackgroundDrawable(who);
        }

        @Override
        public void scheduleDrawable(Drawable who, Runnable what, long when) {
            handler.postAtTime(what, when);
        }

        @Override
        public void unscheduleDrawable(Drawable who, Runnable what) {
            handler.removeCallbacks(what);
        }
    };

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void onColorChanged(int color, int bri, boolean initView, boolean prior) {
        if ((flag || prior) && !initView) {
            flag = false;
            float brightness = (float) bri / 255;
            r = (color >> 16) & 0xFF;
            g = (color >> 8) & 0xFF;
            b = color & 0xFF;
            r = (int) (r * brightness);
            g = (int) (g * brightness);
            b = (int) (b * brightness);

            byte[] data = LEDDeviceCMDMgr.getCommandDataForRGBWColor_Bulb(r, g, b);
            ConnectionManager.GetCurrent().SendDataByDeviceUniDs(deviceUniIDs, data);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    flag = true;
                }
            }, flag_time_out);
        }

    }

    @Override
    public void update(Observable observable, Object data) {
        Message msg = mHandler.obtainMessage(1);
        msg.obj = data;
        mHandler.sendMessage(msg);

    }

    private void onReceive(BLEPeripheralClient.ObserversMessage msg) {
        if (msg != null && msg.what == BLEPeripheralClient.ObserversMessage.ObserversMessage_Data && init) {
            r = msg.getIntValue(6);
            g = msg.getIntValue(7);
            b = msg.getIntValue(8);
            w = msg.getIntValue(9);
            power = msg.getIntValue(2);
            ColorFragment colorFragment = (ColorFragment) pages[0];
            WhiteFragment whiteFragment = (WhiteFragment) pages[1];
            if (r + g + b != 0) {
                if (r != g || g != (int) (b * 3.4f)) {
                    colorFragment.setColor(r, g, b);
                } else {
                    whiteFragment.setWhite(r, 2);
                }
            } else {
                whiteFragment.setWhite(w, 1);
            }

            if (mSwitch != null)
                mSwitch.setChecked(power == 0x23);
            init = false;
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            BLEPeripheralClient.ObserversMessage msg2 = (BLEPeripheralClient.ObserversMessage) msg.obj;
            onReceive(msg2);
        }
    };

    @Override
    public void onWarmWhiteInteraction(int bri, boolean initView, boolean prior) {
        if ((flag || prior) && !initView) {
            flag = false;
            w = bri;
            byte[] data = LEDDeviceCMDMgr.getCommandDataForRGBWWarmWhite_Bulb(w);
            ConnectionManager.GetCurrent().SendDataByDeviceUniDs(deviceUniIDs, data);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    flag = true;
                }
            }, flag_time_out);
        }
    }

    @Override
    public void onColdWhiteInteraction(int bri, boolean initView, boolean prior) {
        if ((flag || prior) && !initView) {
            flag = false;
            r = g = w = bri;
            b = (int) (bri / 3.4f);
            byte[] data = LEDDeviceCMDMgr.getCommandDataForRGBWColor_Bulb(r, g, b);
            ConnectionManager.GetCurrent().SendDataByDeviceUniDs(deviceUniIDs, data);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    flag = true;
                }
            }, flag_time_out);
        }
    }

    public class MyPagerAdapter extends FragmentPagerAdapter {

        private final String[] TITLES = { getString(R.string.colors), getString(R.string.white),
                getString(R.string.effect), getString(R.string.music), getString(R.string.alarm) };

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

        @Override
        public Fragment getItem(int position) {
            return pages[position];

        }

    }

}