com.jigarmjoshi.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.jigarmjoshi.MainActivity.java

Source

package com.jigarmjoshi;

import garin.artemiy.sqlitesimple.library.SQLiteSimple;
import garin.artemiy.sqlitesimple.library.util.SimpleDatabaseUtil;

import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlarmManager;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.commonsware.cwac.locpoll.LocationPoller;
import com.jigarmjoshi.adapter.TabsPagerAdapter;
import com.jigarmjoshi.database.EntryDao;
import com.jigarmjoshi.database.LastLocationDao;
import com.jigarmjoshi.model.LastLocation;
import com.jigarmjoshi.model.Report;
import com.jigarmjoshi.service.ConfigService;
import com.jigarmjoshi.service.LocationManager;
import com.jigarmjoshi.service.task.UploaderTask;
import com.jigarmjoshi.utils.FlagState;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to you 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.
 * 
 * @author jigar.joshi
 * 
 */
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

    private PendingIntent pi = null;
    private AlarmManager mgr = null;

    TextView selectedTextView = null;
    TextView unSelectedTextView = null;

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "report", "clean up" };
    private static final int DATABASE_VERSION = ConfigService.getDataBaseVersion();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (SimpleDatabaseUtil.isFirstApplicationStart(this)) {
            Log.i(MainActivity.class.getSimpleName(), "creating database for the first time");
            SQLiteSimple databaseSimple = new SQLiteSimple(this, DATABASE_VERSION);
            databaseSimple.create(Report.class, LastLocation.class);
        } else if (SimpleDatabaseUtil.isFirstStartOnAppVersion(this, DATABASE_VERSION)) {
            Log.i(MainActivity.class.getSimpleName(),
                    "creating database for the first time for this version " + DATABASE_VERSION);

            SQLiteSimple databaseSimple = new SQLiteSimple(this, DATABASE_VERSION);
            databaseSimple.create(Report.class, LastLocation.class);

        }
        // initialize services
        EntryDao.getInstance(this);
        LastLocationDao.getInstance(this);

        // scheduler
        mgr = (AlarmManager) getSystemService(ALARM_SERVICE);

        Intent i = new Intent(this, LocationPoller.class);
        com.jigarmjoshi.service.LocationManager locationManager = com.jigarmjoshi.service.LocationManager
                .getInstance(getApplicationContext());
        List<String> providers = locationManager.getAllProviders();
        boolean fusedSupported = false;
        for (String provider : providers) {
            if (com.jigarmjoshi.service.LocationManager.FUSED_PROVIDER.equals(provider)) {
                fusedSupported = true;
                break;
            }
        }
        i.putExtra(LocationPoller.EXTRA_INTENT, new Intent(this, com.jigarmjoshi.reciever.LocationReceiver.class));
        i.putExtra(LocationPoller.EXTRA_PROVIDER,
                (fusedSupported ? LocationManager.FUSED_PROVIDER : LocationManager.GPS_PROVIDER));

        pi = PendingIntent.getBroadcast(this, 0, i, 0);
        mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0,
                Long.parseLong(ConfigService.get(ConfigService.GPS_TASK_INTERVAL, "40000")), pi);

        // upload task
        Timer timer = new Timer();
        TimerTask timerTask = new UploaderTask(this);
        timer.schedule(timerTask, 0,
                Long.parseLong(ConfigService.get(ConfigService.UPLOAD_TASK_INTERVAL, "40000")));

        selectedTextView = new TextView(this);
        selectedTextView.setTextColor(Color.BLACK);
        selectedTextView.setGravity(Gravity.CENTER);
        selectedTextView.setPaintFlags(Paint.FAKE_BOLD_TEXT_FLAG);

        unSelectedTextView = new TextView(this);
        unSelectedTextView.setTextColor(Color.GRAY);
        unSelectedTextView.setGravity(Gravity.CENTER);
        unSelectedTextView.setPaintFlags(Paint.FAKE_BOLD_TEXT_FLAG);
        // create if first time

        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        actionBar = getActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#40808080")));
        actionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#40808080")));
        setContentView(R.layout.activity_main);

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        boolean first = false;
        for (String tab_name : tabs) {
            Tab tab = actionBar.newTab().setText(tab_name).setTabListener(this);
            if (first) {
                first = false;
                selectedTextView.setText(tab.getText().toString().toUpperCase(Locale.getDefault()));
                tab.setCustomView(selectedTextView);
            } else {
                unSelectedTextView.setText(tab.getText().toString().toUpperCase(Locale.getDefault()));
                tab.setCustomView(unSelectedTextView);
            }
            actionBar.addTab(tab);
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        Toast.makeText(this, getString(R.string.wait_gps), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        selectedTextView.setText(tab.getText().toString().toUpperCase(Locale.getDefault()));
        tab.setCustomView(selectedTextView);
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
        tab.setCustomView(selectedTextView);
        selectedTextView.setText(tab.getText().toString().toUpperCase(Locale.getDefault()));
        tab.setCustomView(selectedTextView);

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        unSelectedTextView.setText(tab.getText().toString().toUpperCase(Locale.getDefault()));
        tab.setCustomView(unSelectedTextView);
    }

    @Override
    protected void onDestroy() {
        mgr.cancel(pi);
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        FlagState.setSleeping(true);
        super.onPause();
    }

    @Override
    protected void onResume() {
        FlagState.setSleeping(false);
        super.onResume();
    }

    public static boolean shouldTryFused() {
        if (FlagState.isFirstGPSRequest()) {
            return true;
        }
        if (FlagState.getFusedWorked() == null) {
            return true;
        }
        return FlagState.getFusedWorked();
    }

    public static boolean shouldTryNetwork() {
        if (FlagState.isFirstGPSRequest()) {
            return true;
        }
        if (FlagState.getNetworkWorked() == null) {
            return true;
        }
        return FlagState.getNetworkWorked();
    }
}