Android Open Source - Weather-app Main Activity






From Project

Back to project page Weather-app.

License

The source code is released under:

Apache License

If you think the Android project Weather-app 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 app.sunshine.juanjo.views.activities;
/*from   w  w w  .j av a 2s .  c  o m*/
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

import app.sunshine.juanjo.R;
import app.sunshine.juanjo.network.SendIdGCM;
import app.sunshine.juanjo.sync.SunshineSyncAdapter;
import app.sunshine.juanjo.views.fragments.DetailFragment;
import app.sunshine.juanjo.views.fragments.ForecastFragment;

public class MainActivity extends ActionBarActivity implements ForecastFragment.Callback {

  /**
   * Substitute you own sender ID here. This is the project number you got
   * from the API Console, as described in "Getting Started."
   */
  String SENDER_ID = "8==D370802630";

  public static final String EXTRA_MESSAGE = "message";
  public static final String PROPERTY_REG_ID = "registration_id";
  private static final String PROPERTY_APP_VERSION = "appVersion";
  private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
  private boolean mTwoPane = false;

  GoogleCloudMessaging gcm;
  AtomicInteger msgId = new AtomicInteger();
  SharedPreferences prefs;
  String regid;

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

    if (findViewById(R.id.weather_detail_container) != null) {

      mTwoPane = true;

      if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
            .replace(R.id.weather_detail_container, new DetailFragment()).commit();
      }
    }

    ForecastFragment forecastFragment = ((ForecastFragment) getSupportFragmentManager()
        .findFragmentById(R.id.fragment_forecast));
    forecastFragment.setUseTodayLayout(!mTwoPane);

    SunshineSyncAdapter.initializeSyncAdapter(this);

    // Check device for Play Services APK. If check succeeds, proceed with
    // GCM registration.
    if (checkPlayServices()) {
      gcm = GoogleCloudMessaging.getInstance(this);
      regid = getRegistrationId(getApplicationContext());

      if (regid.isEmpty()) {
        registerInBackground();
      }
    } else {
      System.out.println("=> No valid Google Play Services APK found.");
    }
  }

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

  /**
   * Check the device to make sure it has the Google Play Services APK. If it
   * doesn't, display a dialog that allows users to download the APK from the
   * Google Play Store or enable it in the device's system settings.
   */
  private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
        GooglePlayServicesUtil.getErrorDialog(resultCode, this,
            PLAY_SERVICES_RESOLUTION_REQUEST).show();
      } else {
        System.out.println("=> This device is not supported.");
        finish();
      }
      return false;
    }
    return true;
  }

  /**
   * Gets the current registration ID for application on GCM service.
   * <p>
   * If result is empty, the app needs to register.
   *
   * @return registration ID, or empty string if there is no existing
   *         registration ID.
   */
  private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
      System.out.println("=> Registration not found.");
      return "";
    }
    // Check if app was updated; if so, it must clear the registration ID
    // since the existing regID is not guaranteed to work with the new
    // app version.
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
      System.out.println("=> App version changed.");
      return "";
    }
    return registrationId;
  }

  /**
   * Stores the registration ID and the app versionCode in the application's
   * {@code SharedPreferences}.
   *
   * @param context
   *            application's context.
   * @param regId
   *            registration ID
   */
  private void storeRegistrationId(Context context, String regId) {
    final SharedPreferences prefs = getGCMPreferences(context);
    int appVersion = getAppVersion(context);
    System.out.println("=> Saving regId on app version " + appVersion);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(PROPERTY_REG_ID, regId);
    editor.putInt(PROPERTY_APP_VERSION, appVersion);
    editor.commit();
  }

  /**
   * @return Application's {@code SharedPreferences}.
   */
  private SharedPreferences getGCMPreferences(Context context) {
    // This sample app persists the registration ID in shared preferences,
    // but
    // how you store the regID in your app is up to you.
    return getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
  }

  /**
   * @return Application's version code from the {@code PackageManager}.
   */
  private static int getAppVersion(Context context) {
    try {
      PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
          context.getPackageName(), 0);
      return packageInfo.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
      // should never happen
      throw new RuntimeException("Could not get package name: " + e);
    }
  }

  /**
   * Registers the application with GCM servers asynchronously.
   * <p>
   * Stores the registration ID and the app versionCode in the application's
   * shared preferences.
   */
  private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
      @Override
      protected String doInBackground(Void... params) {
        String msg = "";
        try {
          if (gcm == null) {
            gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
          }
          regid = gcm.register(SENDER_ID);
          msg = "Device registered, registration ID=" + regid;

          // You should send the registration ID to your server over
          // HTTP, so it
          // can use GCM/HTTP or CCS to send messages to your app.
          sendRegistrationIdToBackend(regid);

          // For this demo: we don't need to send it because the
          // device will send
          // upstream messages to a server that echo back the message
          // using the
          // 'from' address in the message.

          // Persist the regID - no need to register again.
          storeRegistrationId(getApplicationContext(), regid);
        } catch (IOException ex) {
          msg = "Error :" + ex.getMessage();
          // If there is an error, don't just keep trying to register.
          // Require the user to click a button again, or perform
          // exponential back-off.
        }
        return msg;
      }

      @Override
      protected void onPostExecute(String msg) {
        System.out.println("=>" + msg + "\n");
      }
    }.execute(null, null, null);
  }

  /**
   * Sends the registration ID to your server over HTTP, so it can use
   * GCM/HTTP or CCS to send messages to your app. Not needed for this demo
   * since the device sends upstream messages to a server that echoes back the
   * message using the 'from' address in the message.
   */
  private void sendRegistrationIdToBackend(String id) {
    System.out.println("=> send registration ID");
    // FIXME Set your server ip here.
    String url_server = "http://192.168.1.130:3000/register/" + id;
    new SendIdGCM().execute(url_server);

  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, 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();
    if (id == R.id.action_settings) {
      Intent intent = new Intent(this, SettingsActivity.class);
      startActivity(intent);
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override
  public void onItemSelected(String date) {
    if (mTwoPane) {
      // In two-pane mode, show the detail view in this activity by
      // adding or replacing the detail fragment using a
      // fragment transaction.
      Bundle args = new Bundle();
      args.putString(DetailActivity.DATE_KEY, date);

      DetailFragment fragment = new DetailFragment();
      fragment.setArguments(args);

      getSupportFragmentManager().beginTransaction()
          .replace(R.id.weather_detail_container, fragment).commit();

    } else {
      Intent intent = new Intent(this, DetailActivity.class).putExtra(
          DetailActivity.DATE_KEY, date);
      startActivity(intent);
    }
  }
}




Java Source Code List

app.sunshine.juanjo.gcm.GcmBroadcastReceiver.java
app.sunshine.juanjo.gcm.GcmIntentService.java
app.sunshine.juanjo.network.APIHTTP.java
app.sunshine.juanjo.network.HttpRequest.java
app.sunshine.juanjo.network.SendIdGCM.java
app.sunshine.juanjo.sync.SunshineAuthenticatorService.java
app.sunshine.juanjo.sync.SunshineAuthenticator.java
app.sunshine.juanjo.sync.SunshineSyncAdapter.java
app.sunshine.juanjo.sync.SunshineSyncService.java
app.sunshine.juanjo.util.Utility.java
app.sunshine.juanjo.util.WeatherContract.java
app.sunshine.juanjo.util.WeatherDbHelper.java
app.sunshine.juanjo.util.WeatherJsonParser.java
app.sunshine.juanjo.util.WeatherProvider.java
app.sunshine.juanjo.views.MyView.java
app.sunshine.juanjo.views.activities.DetailActivity.java
app.sunshine.juanjo.views.activities.MainActivity.java
app.sunshine.juanjo.views.activities.SettingsActivity.java
app.sunshine.juanjo.views.adapter.ForecastAdapter.java
app.sunshine.juanjo.views.fragments.DetailFragment.java
app.sunshine.juanjo.views.fragments.ForeCastFragment.java