Android Open Source - android.bigredsnapshot Choose Camera Activity






From Project

Back to project page android.bigredsnapshot.

License

The source code is released under:

MIT License

If you think the Android project android.bigredsnapshot listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package io.evercam.bigredsnapshot;
//from  www.  j av a  2s. c  om
import io.evercam.API;
import io.evercam.Camera;
import io.evercam.EvercamException;
import io.evercam.User;
import io.evercam.bigredsnapshot.helper.CustomedDialog;
import io.evercam.bigredsnapshot.helper.PrefsManager;
import io.evercam.bigredsnapshot.helper.PropertyReader;
import io.evercam.bigredsnapshot.tasks.CheckInternetTask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bugsense.trace.BugSenseHandler;

import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;

public class ChooseCameraActivity extends ListActivity
{
  private final String TAG = "bigredsnapshot-ChooseCameraActivity";
  private final String STATUS_ONLINE = "Online";
  private final String STATUS_OFFLINE = "Offline";

  private SharedPreferences sharedPrefs;
  private ArrayList<HashMap<String, Object>> cameraArrayList;
  private MyAdapter cameraListAdapter;
  private ArrayList<Camera> legalCameras = new ArrayList<Camera>();
  private String userApiKey;
  private String userApiId;
  private String username;
  private ProgressDialog progressDialog;
  private MenuItem menuRefresh;
  private SparseArray<Bitmap> bitArray;
  private SparseArray<String> urlArray;
  private SparseArray<String> urlStatusArray;
  private SparseBooleanArray imageLoadStatusArray;
  private PropertyReader propertyReader;
  private GetCamerasTask getCamerasTask = null;

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

    setContentView(R.layout.activity_choose_camera);
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ChooseCameraActivity.this);
    bitArray = new SparseArray<Bitmap>();// Bitmap images for each camera
    urlArray = new SparseArray<String>();// Working URLs for each camera
    urlStatusArray = new SparseArray<String>();// URL status to show which
                          // URL should be used to
                          // fetch snapshot
    imageLoadStatusArray = new SparseBooleanArray();// Camera image is
                            // returned or
    cameraArrayList = new ArrayList<HashMap<String, Object>>();

    /* BugSense */
    propertyReader = new PropertyReader(getApplicationContext());
    if (propertyReader.isPropertyExist(PropertyReader.KEY_BUG_SENSE))
    {
      String bugSenseCode = propertyReader.getPropertyStr(PropertyReader.KEY_BUG_SENSE);
      BugSenseHandler.initAndStartSession(ChooseCameraActivity.this, bugSenseCode);
    }

    BigRedSnapshot.sendScreenAnalytics(this, getString(R.string.screen_camera_list));

    final ListView listView = this.getListView();
    cameraListAdapter = new MyAdapter(this, cameraArrayList, R.layout.camera_list_layout,
        new String[] { "snapshot_img", "camera_id", "camera_name", "camera_status" },
        new int[] { R.id.snapshot_img, R.id.camera_id_value, R.id.camera_name_value,
            R.id.camera_status_value });
    listView.setAdapter(cameraListAdapter);

    listView.setOnItemClickListener(new OnItemClickListener(){
      @Override
      public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3)
      {
        String urlStatus = urlStatusArray.get(position);

        @SuppressWarnings("unchecked")
        HashMap<String, Object> map = (HashMap<String, Object>) listView
            .getItemAtPosition(position);
        String cameraId = (String) map.get("camera_id");

        if (urlStatus != null)
        {
          if (urlStatus.equals(UrlStatus.LATEST))
          {
            Toast.makeText(ChooseCameraActivity.this, R.string.camera_offline,
                Toast.LENGTH_SHORT).show();
          }
          else
          {
            if (!urlStatus.equals(UrlStatus.EVERCAM))
            {
              launchBigButtonPage(cameraId, urlArray.get(position));
            }
            else
            {
              launchBigButtonPage(cameraId, null);
            }
          }
        }
        else
        // If camera online status is still pending
        {
          launchBigButtonPage(cameraId, null);
        }
      }
    });

    launchGetCameras();
  }

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

    if (propertyReader.isPropertyExist(PropertyReader.KEY_BUG_SENSE))
    {
      BugSenseHandler.startSession(this);
    }
  }

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

    if (propertyReader.isPropertyExist(PropertyReader.KEY_BUG_SENSE))
    {
      BugSenseHandler.closeSession(this);
    }
  }

  @Override
  protected void onRestart()
  {
    super.onRestart();
    new CheckInternetChooseCamera(ChooseCameraActivity.this).execute();
  }

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

  @Override
  public void onBackPressed()
  {
    // not allowed to go back to sign in page.
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    getMenuInflater().inflate(R.menu.choose_camera, menu);
    menuRefresh = menu.findItem(R.id.menu_refresh);
    return true;
  }

  @Override
  public boolean onMenuItemSelected(int featureId, MenuItem item)
  {
    if (item.getItemId() == R.id.menu_refresh)
    {
      BigRedSnapshot.sendEventAnalytics(this, R.string.category_camera_list_clicks,
          R.string.action_refresh, R.string.label_refresh);
      cameraArrayList.clear();
      imageLoadStatusArray.clear();
      bitArray.clear();
      urlArray.clear();
      urlStatusArray.clear();
      legalCameras.clear();
      cameraListAdapter.notifyDataSetChanged();
      launchGetCameras();
    }
    else if (item.getItemId() == R.id.action_signOut)
    {
      showConfirmLogout();
    }
    return false;
  }

  private void showConfirmLogout()
  {
    AlertDialog comfirmLogoutDialog = new AlertDialog.Builder(ChooseCameraActivity.this)

    .setMessage(R.string.comfirmLogOutMsg)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener(){
          @Override
          public void onClick(DialogInterface dialog, int which)
          {
            BigRedSnapshot.sendEventAnalytics(ChooseCameraActivity.this,
                R.string.category_camera_list_clicks, R.string.action_logout,
                R.string.label_logout_from_list);

            PrefsManager.clearEvercamCredential(sharedPrefs);

            Intent intentLogin = new Intent();
            intentLogin.setClass(ChooseCameraActivity.this, LoginActivity.class);
            startActivity(intentLogin);
          }
        }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener(){
          @Override
          public void onClick(DialogInterface dialog, int which)
          {
            return;
          }
        }).create();
    comfirmLogoutDialog.show();
  }

  private class MyAdapter extends SimpleAdapter
  {
    public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource,
        String[] from, int[] to)
    {
      super(context, data, resource, from, to);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
      View superView = super.getView(position, convertView, parent);
      ImageView imageView = (ImageView) superView.findViewById(R.id.snapshot_img);
      ProgressBar progressBar = (ProgressBar) superView.findViewById(R.id.progress);
      TextView statusValue = (TextView) superView.findViewById(R.id.camera_status_value);

      updateOnlineStatus(statusValue, position);

      if (bitArray.get(position) == null)
      {
        // If no image received but image loading already finished
        if (imageLoadStatusArray.get(position) == true)
        {
          statusValue.setText(STATUS_OFFLINE);
          statusValue.setTextColor(Color.RED);
          imageView.setVisibility(View.VISIBLE);
          // imageView.setBackgroundResource(R.drawable.question_grey_trans);
          progressBar.setVisibility(View.GONE);
        }
      }
      else
      // if image received
      {
        statusValue.setVisibility(View.VISIBLE);

        progressBar.setVisibility(View.GONE);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageBitmap(bitArray.get(position));
      }

      return superView;
    }
  }

  private class SingleSnapshotTask extends AsyncTask<Void, Void, Bitmap>
  {
    Camera camera;
    int position;

    SingleSnapshotTask(Camera camera, int position)
    {
      this.camera = camera;
      this.position = position;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap)
    {
      bitArray.put(position, bitmap);

      imageLoadStatusArray.put(position, true);

      cameraListAdapter.notifyDataSetChanged();
    }

    @Override
    protected Bitmap doInBackground(Void... arg0)
    {
      API.setUserKeyPair(userApiKey, userApiId);
      try
      {
        if (camera.isOnline())
        {
          if (camera.hasCredentials())
          {
            Bitmap internalBitmap = SnapshotRequest.getInternalSnapshotBit(camera);
            if (internalBitmap == null)
            {
              Bitmap bitmapExternal = SnapshotRequest.getExternalSnapshotBit(camera);
              if (bitmapExternal == null)
              {
                Bitmap bitmapEvercam = SnapshotRequest
                    .getSnapshotBitFromEvercam(camera);
                if (bitmapEvercam == null)
                {
                  urlStatusArray.put(position, UrlStatus.LATEST);
                  return SnapshotRequest.getLatestSnapshot(camera);
                }
                else
                {
                  urlStatusArray.put(position, UrlStatus.EVERCAM);
                  return bitmapEvercam;
                }
              }
              else
              {
                urlArray.put(position, camera.getExternalJpgUrl());
                urlStatusArray.put(position, UrlStatus.REMOTE);
                return bitmapExternal;
              }
            }
            else
            {
              urlArray.put(position, camera.getInternalJpgUrl());
              urlStatusArray.put(position, UrlStatus.LOCAL);
              return internalBitmap;
            }
          }
          else
          {
            Bitmap evercamBitmap = SnapshotRequest.getSnapshotBitFromEvercam(camera);
            if (evercamBitmap == null)
            {
              urlStatusArray.put(position, UrlStatus.LATEST);
              return SnapshotRequest.getLatestSnapshot(camera);
            }
            else
            {
              urlStatusArray.put(position, UrlStatus.EVERCAM);
              return evercamBitmap;
            }
          }
        }
        else
        // If camera is offline with Evercam
        {
          Bitmap bitmap = SnapshotRequest.getInternalSnapshotBit(camera);
          if (bitmap == null)
          {
            urlStatusArray.put(position, UrlStatus.LATEST);
            return SnapshotRequest.getLatestSnapshot(camera);
          }
          else
          {
            urlArray.put(position, camera.getInternalJpgUrl());
            urlStatusArray.put(position, UrlStatus.LOCAL);
            return bitmap;
          }
        }
      }
      catch (EvercamException e)
      {
        Log.v(TAG, "EvercamException-position" + position + e.getMessage());
        return null;
      }
      catch (Exception e)
      {
        Log.e(TAG, e.toString());
        return null;
      }
    }
  }

  private void launchBigButtonPage(String cameraId, String url)
  {
    Intent intentMain = new Intent();
    intentMain.setClass(ChooseCameraActivity.this, BigButtonActivity.class);
    intentMain.putExtra("url", url);
    intentMain.putExtra("cameraID", cameraId);
    startActivity(intentMain);
  }

  private class GetCamerasTask extends AsyncTask<Void, Camera, ArrayList<Camera>>
  {
    ArrayList<Camera> cameras = null;

    public GetCamerasTask()
    {
      readUserAuthenticationDetails();
    }

    @Override
    protected ArrayList<Camera> doInBackground(Void... params)
    {
      try
      {
        API.setUserKeyPair(userApiKey, userApiId);
        cameras = User.getCameras(username, true);
        if (cameras != null)
        {
          for (Camera camera : cameras)
          {
            publishProgress(camera);
          }
        }
      }
      catch (EvercamException e)
      {
        Log.e(TAG, e.getMessage());
      }
      catch (Exception e)
      {
        CustomedDialog.getAlertDialog(ChooseCameraActivity.this, getString(R.string.error),
            getString(R.string.msg_evercam_error)).show();
      }
      return cameras;
    }

    @Override
    protected void onProgressUpdate(Camera... publishedCameras)
    {
      Camera camera = publishedCameras[0];
      HashMap<String, Object> map = new HashMap<String, Object>();

      try
      {
        map.put("camera_id", camera.getId());
        map.put("camera_name", camera.getName());
        map.put("camera_status", camera.isOnline() ? STATUS_ONLINE : STATUS_OFFLINE);
        cameraArrayList.add(map);
        cameraListAdapter.notifyDataSetChanged();
        legalCameras.add(camera);
      }
      catch (EvercamException e)
      {
        Log.e(TAG, e.getMessage());
      }
    }

    @Override
    protected void onPostExecute(ArrayList<Camera> cameras)
    {
      if (progressDialog.isShowing())
      {
        try
        {
          progressDialog.dismiss();
        }
        catch (Exception e)
        {
          Log.e(TAG, e.getMessage());
        }
      }
      if (menuRefresh != null)
      {
        menuRefresh.setIcon(R.drawable.ic_menu_refresh);
        menuRefresh.setVisible(true);
      }

      if (legalCameras != null && !legalCameras.isEmpty())
      {
        for (int count = 0; count < legalCameras.size(); count++)
        {
          SingleSnapshotTask singleTask = new SingleSnapshotTask(legalCameras.get(count),
              count);
          singleTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
      }
    }

    @Override
    protected void onPreExecute()
    {
      progressDialog = ProgressDialog.show(ChooseCameraActivity.this, "", "Loading...", true);
      if (menuRefresh != null)
      {
        menuRefresh.setVisible(false);
      }
    }
  }

  private void launchGetCameras()
  {
    getCamerasTask = new GetCamerasTask();
    getCamerasTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }

  private void readUserAuthenticationDetails()
  {
    userApiKey = PrefsManager.getUserApiKey(sharedPrefs);
    userApiId = PrefsManager.getUserApiId(sharedPrefs);
    username = PrefsManager.getUsername(sharedPrefs);
  }

  private void updateOnlineStatus(TextView textView, int position)
  {
    String urlStatus = urlStatusArray.get(position);
    if (urlStatus != null)
    {
      if (urlStatus.equals(UrlStatus.LATEST))
      {
        textView.setText(STATUS_OFFLINE);
      }
      else if (urlStatus.equals(UrlStatus.LOCAL))
      {
        // If camera is accessible in local network
        textView.setText(STATUS_ONLINE);
      }
    }
    if (textView.getText().toString().equals(STATUS_ONLINE))
    {
      textView.setTextColor(Color.GREEN);
    }
    else if (textView.getText().toString().equals(STATUS_OFFLINE))
    {
      textView.setTextColor(Color.RED);
    }
  }

  private class CheckInternetChooseCamera extends CheckInternetTask
  {
    public CheckInternetChooseCamera(Context context)
    {
      super(context);
    }

    @Override
    protected void onPostExecute(Boolean hasNetwork)
    {
      if (!hasNetwork)
      {
        CustomedDialog.getNoInternetDialog(ChooseCameraActivity.this).show();
      }
      else
      {
        BigRedSnapshot.sendScreenAnalytics(ChooseCameraActivity.this,
            getString(R.string.screen_camera_list));
      }
    }
  }
}




Java Source Code List

io.evercam.bigredsnapshot.BigButtonActivity.java
io.evercam.bigredsnapshot.BigRedSnapshot.java
io.evercam.bigredsnapshot.ChooseCameraActivity.java
io.evercam.bigredsnapshot.LoginActivity.java
io.evercam.bigredsnapshot.SignUpActivity.java
io.evercam.bigredsnapshot.SlideActivity.java
io.evercam.bigredsnapshot.SnapshotRequest.java
io.evercam.bigredsnapshot.UrlStatus.java
io.evercam.bigredsnapshot.account.AccountUtils.java
io.evercam.bigredsnapshot.account.ProfileQuery.java
io.evercam.bigredsnapshot.account.UserProfile.java
io.evercam.bigredsnapshot.helper.CustomedDialog.java
io.evercam.bigredsnapshot.helper.PrefsManager.java
io.evercam.bigredsnapshot.helper.PropertyReader.java
io.evercam.bigredsnapshot.tasks.CaptureSnapshotTask.java
io.evercam.bigredsnapshot.tasks.CheckInternetTask.java