com.licenta.android.licenseapp.activity.MainTabActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.licenta.android.licenseapp.activity.MainTabActivity.java

Source

package com.licenta.android.licenseapp.activity;

import android.app.DialogFragment;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Toast;

import com.facebook.appevents.AppEventsLogger;
import com.licenta.android.licenseapp.location.LocationService;
import com.licenta.android.licenseapp.R;
import com.licenta.android.licenseapp.adapter.SectionsPagerAdapter;
import com.licenta.android.licenseapp.alert.message.Message;
import com.licenta.android.licenseapp.alert.MessageFactory;
import com.licenta.android.licenseapp.contacts.ContactsActivity;
import com.licenta.android.licenseapp.alarm.AlarmFragment;
import com.licenta.android.licenseapp.location.MapFragment;
import com.licenta.android.licenseapp.fragment.PinDialogFragment;
import com.licenta.android.licenseapp.model.Contact;
import com.licenta.android.licenseapp.model.LocationPoint;
import com.licenta.android.licenseapp.util.Constants;
import com.licenta.android.licenseapp.util.ServiceUtils;
import com.licenta.android.licenseapp.view.NoSwipeViewPager;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;

public class MainTabActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    public SectionsPagerAdapter mSectionsPagerAdapter;
    private NoSwipeViewPager mViewPager;

    //    public FloatingActionButton mAlarmFab;
    //    private FloatingActionButton mSafeFab;
    private SharedPreferences prefs;
    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_tab);

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        realm = Realm.getDefaultInstance();

        int notificationId = getIntent().getIntExtra(Constants.KEY_NOTIFICATION_ID, -1);
        handleNotificationAction(notificationId);

        // UI
        setUpNavigationDrawer();
        setUpViewPager();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.panic_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Snackbar.make(view, R.string.panic_action_msg, Snackbar.LENGTH_LONG)
                        .setAction(android.R.string.cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showPinDialog(false);
                            }
                        }).setCallback(new Snackbar.Callback() {
                            @Override
                            public void onDismissed(Snackbar snackbar, int event) {
                                switch (event) {
                                case Snackbar.Callback.DISMISS_EVENT_ACTION:

                                    break;
                                case Snackbar.Callback.DISMISS_EVENT_TIMEOUT:
                                    Toast.makeText(MainTabActivity.this, R.string.sending_alert, Toast.LENGTH_LONG)
                                            .show();
                                    // TODO send alert

                                    sendAlert();
                                    startLocationService();
                                    break;
                                }
                            }
                        }).show();
            }
        });
        fab.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Snackbar.make(v, R.string.calling_112, Snackbar.LENGTH_LONG)
                        .setAction(android.R.string.cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showPinDialog(false);
                            }
                        }).setCallback(new Snackbar.Callback() {
                            @Override
                            public void onDismissed(Snackbar snackbar, int event) {
                                switch (event) {
                                case Snackbar.Callback.DISMISS_EVENT_ACTION:

                                    break;
                                case Snackbar.Callback.DISMISS_EVENT_TIMEOUT:

                                    // TODO send alert
                                    break;
                                }
                            }
                        }).show();
                return true;
            }
        });

    }

    private void setUpNavigationDrawer() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

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

    private void setUpViewPager() {
        ArrayList<Fragment> pageFragments = new ArrayList<>();
        pageFragments.add(new AlarmFragment());
        pageFragments.add(new MapFragment());
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), pageFragments);

        mViewPager = (NoSwipeViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setPagingEnabled(false);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //                switch (position) {
                //                    case 0:
                //                        mAlarmFab.setVisibility(View.VISIBLE);
                //                        mSafeFab.setVisibility(View.VISIBLE);
                //                        break;
                //                    case 1:
                //                        mAlarmFab.setVisibility(View.GONE);
                //                        mSafeFab.setVisibility(View.GONE);
                //                        break;
                //                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
    }

    @Override
    protected void onPause() {
        super.onPause();

        // FB: Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }

    @Override
    protected void onResume() {
        int notificationId = getIntent().getIntExtra(Constants.KEY_NOTIFICATION_ID, -1);
        //handleNotificationAction(notificationId);

        //mViewPager.setCurrentItem(0);
        super.onResume();

        // FB: Logs 'install' and 'app activate' App Events.
        AppEventsLogger.activateApp(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        realm.close();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (mViewPager.getCurrentItem() > 0) {
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
            } else {
                super.onBackPressed();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_tab, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_account) {
            startActivity(new Intent(this, LoginActivity.class));
        } else if (id == R.id.nav_contacts) {
            startActivity(new Intent(this, ContactsActivity.class));
        } else if (id == R.id.nav_settings) {
            startActivity(new Intent(this, SettingsActivity.class));
        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //    /**
    //     * A placeholder fragment containing a simple view.
    //     */
    //    public static class PlaceholderFragment extends Fragment {
    //        /**
    //         * The fragment argument representing the section number for this
    //         * fragment.
    //         */
    //        private static final String ARG_SECTION_NUMBER = "section_number";
    //
    //        public PlaceholderFragment() {
    //        }
    //
    //        /**
    //         * Returns a new instance of this fragment for the given section
    //         * number.
    //         */
    //        public static PlaceholderFragment newInstance(int sectionNumber) {
    //            PlaceholderFragment fragment = new PlaceholderFragment();
    //            Bundle args = new Bundle();
    //            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    //            fragment.setArguments(args);
    //            return fragment;
    //        }
    //
    //        @Override
    //        public View onCreateView(LayoutInflater inflater, ViewGroup container,
    //                                 Bundle savedInstanceState) {
    //            View rootView = inflater.inflate(R.layout.fragment_alarm, container, false);
    //            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
    //            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
    //            return rootView;
    //        }
    //    }

    private void handleNotificationAction(int notificationId) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        switch (notificationId) {
        case Constants.PANIC_ID:

            notificationManager.cancel(notificationId);
            break;
        case Constants.ALARM_ID:
            if (getIntent().getBooleanExtra(Constants.KEY_DISMISS_ALARM, false)) {
                showPinDialog(true);
                //AlarmReceiver.cancelAlarm(this);
            } else {

            }

            notificationManager.cancel(notificationId);
            break;
        }
    }

    public void showPinDialog(boolean dismissAlarm) {
        // Create the fragment and show it as a dialog.
        DialogFragment dialog = PinDialogFragment.newInstance("",
                dismissAlarm ? getString(R.string.enter_pin_to_dismiss_alarm)
                        : getString(R.string.enter_pin_to_cancel_alert),
                dismissAlarm);
        dialog.show(getFragmentManager(), "pin_dialog");
    }

    private void startLocationService() {
        Intent intent = new Intent(MainTabActivity.this, LocationService.class);
        if (!ServiceUtils.isServiceRunning(MainTabActivity.this, LocationService.class)) {
            startService(intent);
            Toast.makeText(MainTabActivity.this, "Service started", Toast.LENGTH_SHORT).show();
        } else {
            stopService(intent);
            Toast.makeText(MainTabActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendAlert() {
        MessageFactory alertMsgFactory = new MessageFactory();

        List<Contact> contactList = realm.where(Contact.class).equalTo("active", true).findAll();
        LocationPoint lastKnownLocation;
        String messageText = "I may be in danger. My last known location is:  "
                + prefs.getString(Constants.PREF_KEY_LAST_KNOWN_ADDRESS, "");

        for (Contact contact : contactList) {
            for (Message alertMsg : alertMsgFactory.getMessageQueue()) {
                // TODO: handlers
                alertMsg.send(this, contact, messageText);
            }
        }
    }
}