Java tutorial
/* * Copyright 2013 Google Inc. * * 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.soft.pushsender; import android.app.ActionBar; import android.app.FragmentTransaction; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.graphics.Point; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.FragmentManager; import android.support.v4.util.LruCache; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Display; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.widget.ListView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.vk.sdk.VKScope; import com.vk.sdk.VKSdk; import com.vk.sdk.VKUIHelper; import com.vk.sdk.api.VKApi; import com.vk.sdk.api.VKApiConst; import com.vk.sdk.api.VKParameters; import com.vk.sdk.api.VKRequest; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Main UI for the demo app. */ public class DemoActivity extends ActionBarActivity implements ActionBar.TabListener, IStateHolder { public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; public static final String TAG = "GCM Demo"; public static String SENDER_ID = "390960605620"; public static int width; public static int height; public static String sTokenKey = "VK_ACCESS_TOKEN"; public static String appId = "4751425"; public static String[] sMyScope = new String[] { VKScope.FRIENDS, VKScope.WALL, VKScope.PHOTOS, VKScope.NOHTTPS }; GoogleCloudMessaging gcm; Context context; String regid; Map<String, String> aMap = new HashMap<>(); private ArrayList<Items> items = new ArrayList<Items>(); DrawerLayout mDrawerLayout; ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private VKRequest request; final ArrayList<Users> users = new ArrayList<Users>(); private ProgressDialog pdia; android.support.v4.app.Fragment fragment; public static LruCache<String, Bitmap> mMemoryCache = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); VKUIHelper.onCreate(this); VKSdk.authorize(sMyScope, false, false); setContentView(R.layout.drawer_layout); initCache(); //Init drawer left menu initDrawerMenu(); context = getApplicationContext(); //Enable push notifications enPush(); // Check device for Play Services APK. If check succeeds, proceed with GCM registration. checkPlayService_(); setItems(); request = VKApi.friends().get(VKParameters.from(VKApiConst.FIELDS, "sex,photo_200")); fragment = new FragmentForDrawer(); //fragment = new DummySectionFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); if (VKSdk.isLoggedIn()) { Log.i(TAG, "Logged in"); } getScreenSize(); } private void initCache() { if (mMemoryCache == null) { final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size will be measured in kilobytes rather than // number of items. return bitmap.getByteCount() / 1024; } }; } } private void initDrawerMenu() { mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.app_name, R.string.hello_world) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); getActionBar().setTitle("Closed"); //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getActionBar().setTitle("Opened"); //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; } private void enPush() { //Enable push notifications ComponentName receiver = new ComponentName(context, GcmBroadcastReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); } private void checkPlayService_() { // Check device for Play Services APK. If check succeeds, proceed with GCM registration. if (checkPlayServices()) { gcm = GoogleCloudMessaging.getInstance(this); regid = getRegistrationId(context); Log.i(TAG, "Google Play Services APK found."); aMap.put("regid", regid); Log.i(TAG, regid); if (regid.isEmpty()) { registerInBackground(); Log.i(TAG, "registerInBackground was run"); } } else { Log.i(TAG, "No valid Google Play Services APK found."); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } public void setItems() { for (int i = 0; i < 20; i++) { items.add(new Items(i, "name" + i, "description" + i)); Log.i(DemoActivity.TAG, "name " + i + " description"); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { //mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { } @Override protected void onResume() { super.onResume(); VKUIHelper.onResume(this); // Check device for Play Services APK. 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(); Log.i(TAG, "Daaa"); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } /** * 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); Log.i(TAG, "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(); } /** * Gets the current registration ID for application on GCM service, if there is one. * <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()) { Log.i(TAG, "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) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } /** * 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(context); } 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(); // 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(context, 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) { //tv.append(msg + "\n"); } }.execute(null, null, null); } // Send an upstream message. @Override protected void onDestroy() { super.onDestroy(); VKUIHelper.onDestroy(this); } /** * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); Log.i(TAG, "Current version: " + packageInfo.versionCode); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } /** * @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(DemoActivity.class.getSimpleName(), Context.MODE_PRIVATE); } /** * 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() { // Your implementation here. } public void getScreenSize() { Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); width = size.x; height = size.y; } @Override public int getScreenW() { return width; } @Override public int getScreenH() { return height; } @Override public Map<String, String> getStatus() { return aMap; } @Override public GoogleCloudMessaging getGcm() { return gcm; } @Override public Context getContext() { return DemoActivity.this; } @Override public ArrayList<Items> getItems() { return items; } @Override public android.support.v4.app.FragmentManager getSFM() { return getSupportFragmentManager(); } @Override public VKRequest getRequest() { return request; } @Override public void authorize() { } @Override public ArrayList<Users> getUsers() { return users; } }