Back to project page sdk-android-2.
The source code is released under:
Apache License
If you think the Android project sdk-android-2 listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
/** * Copyright 2013 Medium Entertainment, Inc. *//from w ww . j av a 2s .co m * 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.playhaven.android.diagnostic; import android.app.Activity; import android.content.*; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.*; import com.playhaven.android.Placement; import com.playhaven.android.PlacementListener; import com.playhaven.android.PlayHaven; import com.playhaven.android.PlayHavenException; import com.playhaven.android.data.CustomEvent; import com.playhaven.android.data.DataCollectionField; import com.playhaven.android.data.Purchase; import com.playhaven.android.data.Reward; import com.playhaven.android.push.GCMRegistrationRequest; import com.playhaven.android.push.NotificationBuilder; import com.playhaven.android.push.PushReceiver; import com.playhaven.android.req.*; import com.playhaven.android.view.*; import com.playhaven.android.diagnostic.OutputBox.OutputType; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class Launcher extends Activity implements PlacementListener, AdapterView.OnItemSelectedListener, RequestListener, DialogInterface.OnDismissListener, PlayHavenListener { private RequestType getRequestTypeForTitle(String title) { // RequestType.valueOf doesn't work since we are comparing to an autogenerated field Resources res = getResources(); for(RequestType type : RequestType.values()) { if(type.toString(res).equals(title)) return type; } return null; } private OutputType getOutputTypeForTitle(String title) { // RequestType.valueOf doesn't work since we are comparing to an autogenerated field Resources res = getResources(); for(OutputType type : OutputType.values()) { if(type.toString(res).equals(title)) return type; } return null; } public enum ViewType { Activity(R.string.view_activity), Dialog(R.string.view_dialog); ViewType(int id) { this.id = id; } private int id; public String toString(Resources resources){return resources.getString(id);} } private ViewType getViewTypeForTitle(String title) { // ViewType.valueOf doesn't work since we are comparing to an autogenerated field Resources res = getResources(); for(ViewType type : ViewType.values()) { if(type.toString(res).equals(title)) return type; } return null; } public static final String TAG = "PHDiagnosticApp"; private static final int PH_REQUEST_CODE = 12345; private static final int MNU_SETTINGS = 0; private static final int MNU_API_TEST = 1; private static final int MNU_TOGGLE_FS =2; private Placement placement; private Handler handler; private Spinner reqSpinner; private Spinner viewSpinner; private Spinner outputSpinner; private GCMReceiver pushReceiver; private OutputBox mOutputBox; private boolean mIsFullscreen = false; private PlayHavenRequest request; private TextView.OnEditorActionListener editTextListener = new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { /** * Using the text watcher would cause us to set placement on the more games too often * So we will instead just watch for it to be done */ if (actionId != EditorInfo.IME_ACTION_DONE) return false; EditText text = (EditText)v; String placementTag = text.getText().toString(); if(placementTag == null || placementTag.length() == 0) return false; updatePlayHaven(); placementTag = getPlacementTag(); if(placementTag == null) return false; MoreGames more = (MoreGames) findViewById(R.id.more); more.setPlacementTag(placementTag); more.load(Launcher.this); return true; } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); super.onCreate(savedInstanceState); handler = new Handler(); setContentView(R.layout.main); mOutputBox = (OutputBox) findViewById(R.id.output); EditText placementEditor = (EditText) findViewById(R.id.placementTag); placementEditor.setOnEditorActionListener(editTextListener); // Setup Request Type Spinner reqSpinner = (Spinner) findViewById(R.id.request_spinner); Resources res = getResources(); RequestTypeAdapter reqAdapter = new RequestTypeAdapter(this); reqAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); reqSpinner.setAdapter(reqAdapter); reqSpinner.setOnItemSelectedListener(this); // Setup PlayHavenView Type Spinner viewSpinner = (Spinner) findViewById(R.id.viewtype_spinner); ArrayList<String> viewTypes = new ArrayList<String>(); for(ViewType type : ViewType.values()) viewTypes.add(type.toString(res)); ArrayAdapter<String> viewAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, viewTypes); viewAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); viewSpinner.setAdapter(viewAdapter); viewSpinner.setOnItemSelectedListener(this); // Setup Ouput Spinner outputSpinner = (Spinner) findViewById(R.id.output_spinner); ArrayList<String> outputTypes = new ArrayList<String>(); for(OutputType type : OutputType.values()) outputTypes.add(type.toString(res)); ArrayAdapter<String> outputAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, outputTypes); outputAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); outputSpinner.setAdapter(outputAdapter); outputSpinner.setOnItemSelectedListener(this); Intent data = getIntent(); PlayHavenView.DismissType dismiss = (PlayHavenView.DismissType) data.getSerializableExtra(PlayHavenView.BUNDLE_DISMISS_TYPE); Log.d(TAG, "Ad was closed: " + dismiss); Bundle adData = data.getBundleExtra(PlayHavenView.BUNDLE_DATA); mOutputBox.updateResult(extractBundle(adData)); } @Override protected void onNewIntent(Intent intent) { Log.d(TAG, "onNewIntent:"); super.onNewIntent(intent); setIntent(intent); Bundle bundle = intent.getExtras(); if(bundle != null) { PlayHavenView.DismissType dismiss = (PlayHavenView.DismissType) intent.getSerializableExtra(PlayHavenView.BUNDLE_DISMISS_TYPE); Log.d(TAG, "Ad was closed: " + dismiss); Bundle adData = intent.getBundleExtra(PlayHavenView.BUNDLE_DATA); mOutputBox.updateResult(extractBundle(adData)); String content_id = bundle.getString(PushReceiver.PushParams.content_id.name()); if(content_id != null) Log.d(TAG, "\tcontent_id=" + content_id); String message_id = bundle.getString(PushReceiver.PushParams.message_id.name()); if(message_id != null) Log.d(TAG, "\tmessage_id=" + message_id); String url = bundle.getString(NotificationBuilder.Keys.URI.name()); if(url != null) Log.d(TAG, "\turi=" + Uri.parse(url)); String placementTag = bundle.getString(PlayHavenView.BUNDLE_PLACEMENT_TAG); if(placementTag != null) Log.d(TAG, "\ttag=" + placementTag); else{ Placement placement = bundle.getParcelable(PlayHavenView.BUNDLE_PLACEMENT); if(placement != null) Log.d(TAG, "\tplacement=" + placement.getPlacementTag()); } int options = bundle.getInt(PlayHavenView.BUNDLE_DISPLAY_OPTIONS, -1); if(options != -1) Log.d(TAG, "\toptions=" + options); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, MNU_SETTINGS, 0, "Edit Settings"); menu.add(Menu.NONE, MNU_API_TEST, 1, "Check API Status"); menu.add(Menu.NONE, MNU_TOGGLE_FS, 1, "Toggle Fullscreen"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case MNU_SETTINGS: startActivity(new Intent(this, DiagnosticPreferences.class)); return true; case MNU_API_TEST: startActivity(new Intent(this, APIValidationIndicators.class)); return true; case MNU_TOGGLE_FS: if(mIsFullscreen){ this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } mIsFullscreen = ! mIsFullscreen; return true; } return false; } private JSONObject customDimensions = null; private void updatePlayHaven() { try{ SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); /** * It doesn't allow us to use the integer values * http://code.google.com/p/android/issues/detail?id=2096 * So we could just do Integer.parseInt * but then the preferences show "3" instead of "DEBUG" * so, we'll do it the hard way */ PlayHaven.setLogLevel(DiagnosticPreferences.Pref.pref_log.getString(pref, "INFO")); if(! ((DiagnosticApp)getApplication()).pendingChanges ) return; String token = DiagnosticPreferences.Pref.pref_token.getString(pref, "token"); String secret = DiagnosticPreferences.Pref.pref_secret.getString(pref, "secret"); String projectId = DiagnosticPreferences.Pref.pref_projectid.getString(pref, "push project id"); String server = DiagnosticPreferences.Pref.pref_server.getString(pref); String fileName = DiagnosticPreferences.Pref.pref_file.getString(pref); if(fileName != null && fileName.length() > 0) { PlayHaven.configure(this, fileName); } else { PlayHaven.configure(this, token, secret, projectId); if(server != null && server.length() > 0) { pref = PlayHaven.getPreferences(this); SharedPreferences.Editor editor = pref.edit(); editor.putString(PlayHaven.Config.APIServer.toString(), server); editor.commit(); } } String dimFilename = DiagnosticPreferences.Pref.pref_dimensions.getString(pref); if(dimFilename != null && dimFilename.length() > 0) { try{ customDimensions = (JSONObject) (new JSONParser(JSONParser.MODE_JSON_SIMPLE)).parse(new FileReader(dimFilename)); }catch(Exception e){ Log.e(TAG, "Error obtaining custom dimensions", e); customDimensions = null; } }else{ customDimensions = null; } ((DiagnosticApp)getApplication()).pendingChanges = false; }catch(Exception e){ Log.e(TAG, "Error", e); } } @Override protected void onPause() { if(pushReceiver != null) { unregisterReceiver(pushReceiver); pushReceiver = null; } Log.d(TAG, "onPause"); super.onPause(); } @Override protected void onResume() { Log.d(TAG, "onResume"); super.onResume(); // Have a local receiver to update the UI if we get registration results back. if(pushReceiver == null) { pushReceiver = new GCMReceiver(); IntentFilter pushFilter = new IntentFilter(); pushFilter.addAction(com.playhaven.android.push.GCMBroadcastReceiver.C2DM_RECEIVE); pushFilter.addAction(com.playhaven.android.push.GCMBroadcastReceiver.C2DM_REGISTRATION); pushFilter.addCategory(getPackageName()); registerReceiver(pushReceiver, pushFilter); } } @Override public void onDismiss(DialogInterface dialog) { Windowed diag = (Windowed)dialog; Log.d(TAG, "Dialog was dismissed: " + diag.getPlacementTag()); } public void doRequest(android.view.View target) { Spinner reqSpinner = (Spinner) findViewById(R.id.request_spinner); Spinner viewSpinner = (Spinner) findViewById(R.id.viewtype_spinner); Spinner outputSpinner = (Spinner) findViewById(R.id.output_spinner); mOutputBox.updateRequest(getApplicationContext().getString(R.string.output_hint_text)); outputSpinner.setSelection(0); try { RequestType requestType = getRequestTypeForTitle("" + reqSpinner.getSelectedItem()); ViewType viewType = getViewTypeForTitle("" + viewSpinner.getSelectedItem()); updatePlayHaven(); GCMRegistrationRequest regRequest = null; request = null; switch(requestType) { case Open: OpenRequest open = new OpenRequest(); request = open; open.setResponseHandler(this); if(customDimensions != null) open.addDimensions(customDimensions); open.send(this); return; case GcmReg: regRequest = new GCMRegistrationRequest(); regRequest.register(this); mOutputBox.updateRequest("Registration request sent."); ((RequestTypeAdapter)reqSpinner.getAdapter()).setGCM(this, true); return; case GcmDereg: regRequest = new GCMRegistrationRequest(); regRequest.deregister(this); mOutputBox.updateRequest("De-registration request sent."); ((RequestTypeAdapter)reqSpinner.getAdapter()).setGCM(this, false); return; case CustomEvent: doCustomEvent(); return; default: break; } String placementTag = getPlacementTag(); if(placementTag == null) return; switch(requestType) { case Preload: placement = new Placement(placementTag); if(customDimensions != null) placement.addDimensions(customDimensions); placement.setListener(this); placement.preload(this); mOutputBox.updateRequest("Preloading: " + placementTag); return; default: if(placement == null) break; if(placement.getPlacementTag().equals(placementTag)) break; // Clear outdated placement placement = null; break; } switch(requestType) { case Content: int displayOpts = PlayHavenView.NO_DISPLAY_OPTIONS; if( ((CheckBox)findViewById(R.id.auto)).isChecked() ) { displayOpts |= PlayHavenView.AUTO_DISPLAY_OPTIONS; }else{ if( ((CheckBox)findViewById(R.id.overlay)).isChecked() ) displayOpts |= PlayHavenView.DISPLAY_OVERLAY; if( ((CheckBox)findViewById(R.id.animation)).isChecked() ) displayOpts |= PlayHavenView.DISPLAY_ANIMATION; } switch(viewType) { case Activity: if(!FullScreen.timeElapsed(this, 10000)) Toast.makeText(this, "Quick quick quick!", Toast.LENGTH_SHORT).show(); if(placement != null && placement.getPlacementTag().equals(placementTag)) startActivityForResult(FullScreen.createIntent(this, placement, displayOpts), PH_REQUEST_CODE); else startActivityForResult(FullScreen.createIntent(this, placementTag, displayOpts), PH_REQUEST_CODE); mOutputBox.updateRequest("Launching FullScreen with placement: " + placementTag); break; case Dialog: Windowed dialog = new Windowed(this); dialog.setDisplayOptions(displayOpts); if(placement == null) dialog.setPlacementTag(placementTag); else dialog.setPlacement(placement); dialog.setOnDismissListener(this); dialog.setPlayHavenListener(this); dialog.show(); mOutputBox.updateRequest("Launching Windowed with placement: " + placementTag); break; default: break; } break; case Metadata: MetadataRequest req = new MetadataRequest(placementTag); request = req; req.setResponseHandler(this); req.send(this); break; default: break; } } catch(Exception e) { /* no-openContextMenu() */ } } private void doCustomEvent() { EditText fileEditor = (EditText) findViewById(R.id.eventFile); final String fileName = fileEditor.getText().toString(); if(TextUtils.isEmpty(fileName)) return; new Thread(new Runnable(){ @Override public void run() { try { CustomEvent event = new CustomEvent(new FileReader(new File(fileName))); request = new CustomEventRequest(event); request.setResponseHandler(Launcher.this); if(customDimensions != null) request.addDimensions(customDimensions); request.send(Launcher.this); } catch (Exception e) { Log.e(TAG, "Error sending custom event", e); } } }).start(); } private String getPlacementTag() { String placementId = ((EditText)findViewById(R.id.placementTag)).getText().toString(); if(placementId != null && placementId.length() > 0) return placementId; Toast.makeText(this,"Placement tag must be set", Toast.LENGTH_LONG).show(); return null; } public void doMoreGames(android.view.View target) { updatePlayHaven(); String placementTag = getPlacementTag(); if(placementTag == null) return; int displayOpts = 0; if( ((CheckBox)findViewById(R.id.overlay)).isChecked() ) displayOpts |= PlayHavenView.DISPLAY_OVERLAY; if( ((CheckBox)findViewById(R.id.animation)).isChecked() ) displayOpts |= PlayHavenView.DISPLAY_ANIMATION; startActivityForResult(FullScreen.createIntent(this, "more_games", displayOpts), PH_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(data == null) { PlayHaven.e("onActivityResult received a null intent"); placement = null; return; } if(requestCode == PH_REQUEST_CODE) { Log.d(TAG, "Ad placement was: " + data.getStringExtra(PlayHavenView.BUNDLE_PLACEMENT_TAG)); Log.d(TAG, "Ad display options were: " + data.getStringExtra(PlayHavenView.BUNDLE_PLACEMENT_TAG)); PlayHavenView.DismissType dismiss = (PlayHavenView.DismissType) data.getSerializableExtra(PlayHavenView.BUNDLE_DISMISS_TYPE); Log.d(TAG, "Ad was closed: " + dismiss); String result = String.format( "Placement: %s, display opts: %s, closed by: %s %s", data.getStringExtra(PlayHavenView.BUNDLE_PLACEMENT_TAG), data.getIntExtra(PlayHavenView.BUNDLE_DISPLAY_OPTIONS, 0), dismiss, extractBundle(data.getBundleExtra(PlayHavenView.BUNDLE_DATA)) ); mOutputBox.updateResult(result); Placement pl = data.getParcelableExtra(PlayHavenView.BUNDLE_PLACEMENT); if(pl != null) mOutputBox.updateResponse(pl.getModel()); // Clear out the old placement (don't re-use) placement = null; } } @Override public void onItemSelected(AdapterView<?> parent, android.view.View view, int position, long id) { if(parent == outputSpinner){ final OutputType outType = getOutputTypeForTitle(parent.getItemAtPosition(position).toString()); mOutputBox.updateDisplay(outType); } if(parent != reqSpinner) return; switch(getRequestTypeForTitle(parent.getItemAtPosition(position).toString())) { case Open: bulkUpdateViews(false); break; case Preload: bulkUpdateViews(false); findViewById(R.id.placementTag).setEnabled(true); break; case Content: bulkUpdateViews(true); findViewById(R.id.eventFile).setEnabled(false); break; case Metadata: bulkUpdateViews(false); findViewById(R.id.placementTag).setEnabled(true); break; case CustomEvent: bulkUpdateViews(false); findViewById(R.id.eventFile).setEnabled(true); break; default: break; } findViewById(R.id.go).setEnabled(true); } @Override public void onNothingSelected(AdapterView<?> parent) { bulkUpdateViews(false); } private void bulkUpdateViews(boolean enabled) { findViewById(R.id.placementTag).setEnabled(enabled); findViewById(R.id.eventFile).setEnabled(enabled); findViewById(R.id.auto).setEnabled(enabled); findViewById(R.id.overlay).setEnabled(enabled); findViewById(R.id.animation).setEnabled(enabled); findViewById(R.id.viewtype_spinner).setEnabled(enabled); findViewById(R.id.go).setEnabled(enabled); } @Override public void handleResponse(Context context, final String json) { handler.post(new Runnable(){ @Override public void run() { if(request != null) mOutputBox.updateRequest(request); mOutputBox.updateResponse(json); } }); } @Override public void handleResponse(Context context, final PlayHavenException e) { handler.post(new Runnable(){ @Override public void run() { if(request != null) mOutputBox.updateRequest(request); mOutputBox.updateResponse(e.getMessage()); } }); } @Override public void viewFailed(PlayHavenView view, PlayHavenException exception) { mOutputBox.updateResult(exception.getMessage()); } @Override public void viewDismissed(PlayHavenView view, PlayHavenView.DismissType dismissType, Bundle data) { String result = "PlayHavenView#" + view.getPlacementTag() + " was dismissed: " + dismissType; result += extractBundle(data); mOutputBox.updateResult(result); } @Override public void contentDismissed(Placement placement, PlayHavenView.DismissType dismissType, Bundle data) { PlayHaven.v("Placement: " + placement.getPlacementTag() + " was dismissed: " + dismissType); String result = "Placement: " + placement.getPlacementTag() + " was dismissed: " + dismissType; result += extractBundle(data); mOutputBox.updateResult(result); } @Override public void contentLoaded(Placement placement) { final String model = placement.getModel(); if(model == null) { Log.d(TAG, "Content Loaded: null (" + (this.placement.getModel()==null) + ")"); return; } handler.post(new Runnable() { @Override public void run() { mOutputBox.updateResponse(model); findViewById(R.id.viewtype_spinner).setEnabled(true); } }); } @Override public void contentFailed(Placement placement, PlayHavenException e) { final PlayHavenException exception = e; handler.post(new Runnable() { @Override public void run() { mOutputBox.updateResponse(exception); findViewById(R.id.viewtype_spinner).setEnabled(true); } }); } private class GCMReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { PlayHaven.v("Received registration request in launcher."); String action = intent.getAction(); String output = "Received GCM broadcast. "; if (com.playhaven.android.push.GCMBroadcastReceiver.C2DM_REGISTRATION.equals(action)) { output += " Received registration_id: " + intent.getStringExtra("registration_id"); } else if (com.playhaven.android.push.GCMBroadcastReceiver.C2DM_RECEIVE.equals(action)) { output += " Push notification received."; } mOutputBox.updateResponse(output); } } /** * @param adData a Bundle returned from the Fullscreen Activity * @return a string listing the keys and (for some keys) lists of items in the Bundle */ private String extractBundle(Bundle adData) { String result = ""; if(adData != null) { for(String key : adData.keySet()) { if(PlayHavenView.BUNDLE_DATA_REWARD.equals(key)){ for(Reward reward : adData.<Reward>getParcelableArrayList(PlayHavenView.BUNDLE_DATA_REWARD)){ Log.d(TAG, "Reward: " + reward); result = String.format("%s, Reward: %s", result, reward); } } else if(PlayHavenView.BUNDLE_DATA_PURCHASE.equals(key)){ for(Purchase data : adData.<Purchase>getParcelableArrayList(PlayHavenView.BUNDLE_DATA_PURCHASE)){ Log.d(TAG, "Purchase: " + data); result = String.format("%s, Purchase: %s", result, data); } } else if(PlayHavenView.BUNDLE_DATA_OPTIN.equals(key)){ for(DataCollectionField data : adData.<DataCollectionField>getParcelableArrayList(PlayHavenView.BUNDLE_DATA_OPTIN)){ Log.d(TAG, "DataCollectionField: " + data); result = String.format("%s, DataCollectionField: %s", result, data); } } else { Log.d(TAG, "Additional data @" + key); result = String.format("%s, Ad data @ %s = %s", result, key, adData.get(key)); } } } else { PlayHaven.v("adData was null"); } return result; } }