We are using the Ereza CustomActivityOnCrash library to handle unexpected issues with our android app. It's activity offers some debug output which we enable in develop and test builds but disable on production builds. In addition we want to log that information about crash details (log entries, stack trace, error details) in background.
CustomActivityOnCrash offers to call event listeners which sounds convenient. I wanted to implement the interface in our logging service, however I do not understand how I can access the existing information in the crash activity that way. Which puzzles me, cause isn't that a natural expectation?
Basically I need to access public methods of an android activity object from an event listener method that does not get handed over anything. How can I access that activity in the handler method? And how can I get the intent of the activity leading to the crash which is the argument the crash activity expects in those public methods it offers to access the existing information it offers? The examples given in the libraries documentation and those I could find on the internet are trivial, they only dump example strings, not the actual data collected by the library.
This all sounds counter intuitive to me. Which is why I think I generally miss something here. Maybe someone has a short hint for me to bring me on track again. Thanks!
Here is the basics of the LogService implementation I imagine:
...
import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
...
public class LogService
implements CustomActivityOnCrash.EventListener {
private static LogService instance;
...
public void log(LogLevel level, String message) {
....
}
public void logCrashDetails(String activityLog, String stackTrace, String errorDetails) {
String message = String.format(
"--- CRASH REPORT ---\n\n-- Activity log:\n%s\n\n- Stack trace:\n%s\n\nError details:\n%s",
activityLog,
stackTrace,
errorDetails);
log(LogLevel.ERROR, message);
}
....
// CustomActivityOnCrash EventListener interface
#Override
public void onLaunchErrorActivity() {
log(LogLevel.INFO, "COAC: app crashed");
logCrashDetails(
// CustomActivityOnCrash.getActivityLogFromIntent(...some intent...),
// CustomActivityOnCrash.getStackTraceFromIntent(...some intent...),
// CustomActivityOnCrash.getAllErrorDetailsFromIntent(...some intent...)
);
}
#Override
public void onRestartAppFromErrorActivity() {
log(LogLevel.INFO, "COAC: app restarted");
}
#Override
public void onCloseAppFromErrorActivity() {
log(LogLevel.INFO, "COAC: app closed");
}
}
Related
#Override
public void getLeaderboardGPGS() {
if (gameHelper.isSignedIn()) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(), getString(R.string.event_score)), 100);
}
else if (!gameHelper.isConnecting()) {
loginGPGS();
}
}
#Override
public void getAchievementsGPGS() {
if (gameHelper.isSignedIn()) {
startActivityForResult(Games.Achievements.getAchievementsIntent(gameHelper.getApiClient()), 101);
}
else if (!gameHelper.isConnecting()) {
loginGPGS();
}
}
Can anyone explain to me what these methods do? I have them as part of implementing a GoogleApi interface I made in the context of a tutorial. I especially don't understand the 100 / 101 parts, but the whole thing, in general, is quite confusing for me.
PS. I am making a game in LibGDX and this is my first time touching the Google Play API (or I think any API for that matter)
First Method getLeaderboardGPGS show you Leaderboard above your Activity
if you are already Signed in otherwise it start signing process.
Above method definition is from Libgdx wiki but it should be
private final static int REQUEST_CODE_UNUSED = 9002;
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(), getString(R.string.leaderboardId)), REQUEST_CODE_UNUSED);
REQUEST_CODE_UNUSED is an arbitrary integer for the request code
getString(R.string.leaderboardId) is LEADERBOARD_ID
taken from Google wiki
Second Method getAchievementsGPGS is used to show a player's achievements, call getAchievementsIntent() to get an Intent to create the default achievements UI.
startActivityForResult(Games.Achievements.getAchievementsIntent(gameHelper.getApiClient()), REQUEST_ACHIEVEMENTS);
where REQUEST_ACHIEVEMENTS is an arbitrary integer used as the request code.
I'm trying to implement a Google Fit Listener when data is updated into Google Fit services.
In this link of Google Fit documentation there is a simple example, however, it is not 100% clear. For that reason, I have two problems:
I don't know how to implement mResultCallback variable (there aren't any examples in this documentation).
When I define a simple ResultCallback (it seems to work but I'm not sure) and I launch the application, it gives me a result error code: java.lang.SecurityException: Signature check failed
The code within the HistortyApi lists one of android.permission.ACCESS_FINE_LOCATION or android.permission.BODY_SENSORS as being required.
Adding those permissions to my code hasn't resolved the same problem though.
Confirmed bug in Google Fit services. See discussion in https://plus.google.com/110141422948118561903/posts/Lqri4LVR7cD
mResultCallback is a ResultCallback<Status> so you need to implement a class of that type. Documentation is here, but there's only one method you need to implement:
public abstract void onResult (Status result)
The standard way is to do this using an anonymous class either when you declare mResultCallback or when you're using it as a parameter. Below is an example from Google's BasicRecordingAPI example:
Fitness.RecordingApi.subscribe(mClient, DataType.TYPE_ACTIVITY_SAMPLE)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
if (status.getStatusCode()
== FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
Log.i(TAG, "Existing subscription for activity detected.");
} else {
Log.i(TAG, "Successfully subscribed!");
}
} else {
Log.i(TAG, "There was a problem subscribing.");
}
}
});
If you want to use a member variable you can simply make an assignment instead:
ResultCallback<Status> mResultCallback = new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
...
}
});
Of course you can define a non-anonymous class, but if you did that for every callback you had you would end up creating a LOT of classes.
I am having a problem making a Google Cast Service. I can not seem to find what to use for mSelectedDevice. Both tutorials that I am using do not provide enough explanation for this, and neither go into detail of what mSelectedDevice should be.
public class CastMediaRouterCallback extends MediaRouter.Callback{
#Override
public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo info) {
mSelectedDevice = CastDevice.getFromBundle(info.getExtras());
String routeId = info.getId();
//Startd NanoHTTPD, Find URI of photo/video, and display on Cast device
}
#Override
public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo info) {
teardown();
mSelectedDevice = null;
}
}
(Tutorials I am using: https://developers.google.com/cast/docs/android_sender /// https://www.binpress.com/tutorial/building-an-android-google-cast-sender-app/161)
mSelecteDevice is an instance variable that is of type CastDevice. Not sure what you mean by "Google Cast Service" in your question but it seems you might be better off grabbing a sample project from oue GitHub repo as your starting point.
This is my first post and I did not find anything similar, so I've decided to ask.
Im developing a Poker Game for Android to practice the SDK and refresh/improve my Java. Its a simple app that control a texas hold'em poker hand.
Initally, I wrote my classes using only Java SE and it looks fine. Each class has its own purpose and testing it with console input/output, I can see it really works :)
Last week, I decided to port it to Android to see things happening through a graphic interface, so I got the resource images, make an Activity and included my poker package.
Before port to Android I can just put a println (or readLine) to see whats going on and send my inputs. Now Im stuck in how each class can communicate to the game activity to provide what must be drawn. If possible, I don't want insert Android draw code inside game classes. Im trying find a way to exchange messages between my Activity and the game classes and Id like some suggetions. Im new in developing Android apps, so I dont know all mechanics to do this.
Below are the snippet from my activity:
package my.poker.game;
//import stuff
public class ActivityHand extends Activity
{
private static Vector<Player> Players = new Vector<Player>();
public static final int MAX_PLAYERS = 8;
public static void startEmptyTable()
{
Players.removeAllElements();
Players.setSize(MAX_PLAYERS);
}
public static void LeaveTable(int pos)
{
Players.set(pos, null);
}
public static void SitTable(int pos, Player player)
{
Players.set(pos, player);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int cash = 1000;
startEmptyTable();
SitTable(0, new Jogador("William", cash));
SitTable(2, new Jogador("Richard", cash));
SitTable(4, new Jogador("John", cash));
SitTable(6, new Jogador("Paul", cash));
SitTable(8, new Jogador("Albert", cash));
//Start a Hand.... in future this will be a loop for each Hand
Hand hand = new Hand(Players);
}
}
The object hand, will select a Dealer, deal the cards, control the small and big blinds and start the game loop.
The question is: how the hand class can tell the Activity to Draw and pass an object containing what to draw?
Thanks a lot for your help
Editing: I've decided to try implementing it using a Handler and passing simple messages. As I read from Handler at Developers a Handler object is assigned to thread's MessageQueue, so I tried to put this into my Activity Class (before Hand hand = new Hand (...) ):
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
Bundle bundle = msg.getData();
// Do something with message contents
}
};
And inside the Hand class I put this when I want to draw something:
Handler handler = new Handler();
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("Key", "The Key's Value");
msg.setData(bundle);
handler.sendMessage(msg);
As I understood, both handlers are from same thread, so they are assigned to same MessageQueue right? I tought when I send a message inside Hand class, the Activity class can receive it in handleMessage method and processes any message I send, but handleMessage doesn't execute.
What am I missing?
Thanks again
To call methods in the activity, you want to pass the activity to this class.
for example:
public class PokerActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
Hand hand = new Hand(this);
}
public void setVisibleHand(Player player)
{
<do something in the activity>
}
}
public class Hand
{
PokerActivity pokerActivity;
public Hand(PokerActivity activity)
{
this.pokerActivity = activity;
}
public void setVisibleHand()
{
pokerActivity.setVisibleHand(player1);
}
}
Now, this might not be the best way to do it. In Android you have to be carefull to not leak the context, or you might be getting trouble with the memory. (simply passing the activity/context might be the easy way, but is also the easiest way to leak the context.)
I'd advise you to look at some simple tutorials first, to get a feeling of how android activities work.
You could use a Handler and Message system to communicate between your classes.
This tutorial by Lars Vogel should help you Android Threads, Handlers and AsyncTask - Tutorial
You will have to create another class to make the interactions with your own classes and the activity itself.
From that class you can use the activity context to control the android activity.
The approach about using Handlers and Messages is good but would require you to modify your game classes.
Maybe you should extend View Class to draw the Hand.
http://developer.android.com/reference/android/view/View.html
While simple, interface-driven event notification frameworks in Java have been around since pre-Cambrian times (e.g. java.beans.PropertyChangeSupport), it is becoming increasingly popular for frameworks to use annotation-driven event notification instead.
For an example, see JBossCache 2.2. The listener class has its listener methods annotated, rather than conforming to a rigid interface. This is rather easier to program to, and easier to read, since you don't have to write empty implementations of listener callbacks that you're not interested in (and yes, I know about listener adapter superclasses).
Here's a sample from the JBossCache docs:
#CacheListener
public class MyListener {
#CacheStarted
#CacheStopped
public void cacheStartStopEvent(Event e) {
switch (e.getType()) {
case Event.Type.CACHE_STARTED:
System.out.println("Cache has started");
break;
case Event.Type.CACHE_STOPPED:
System.out.println("Cache has stopped");
break;
}
}
#NodeCreated
#NodeRemoved
#NodeVisited
#NodeModified
#NodeMoved
public void logNodeEvent(NodeEvent ne) {
log("An event on node " + ne.getFqn() + " has occured");
}
}
The problem with this, is that it's very much more of an involved process writing the framework to support this sort of thing, due to the annotation-reflection nature of it.
So, before I charge off down the road of writing a generic framework, I was hoping someone had done it already. Has anyone come across such a thing?
You can already do this today with EventBus.
Following example is from EventBus Getting Started guide. Statusbar that updates based on published events, and no need to register statusbar control/widget as listener of publisher(s). Without EventBus, statusbar will need to be added as listener to many classes. Statusbar can also be created and destroyed at any time.
public StatusBar extends JLabel {
public StatusBar() {
AnnotationProcessor.process(this);
}
#EventSubscriber(eventClass=StatusEvent.class)
public void updateStatus(StatusEvent statusEvent) {
this.setText(statusEvent.getStatusText();
}
}
A similar project is ELF (Event Listener Framework) but it seems to be less mature.
I'm currently researching about event notification frameworks on Publish-Subscribe Event Driven Programming | Kev's Spring vs Java EE Dev and the followup articles.
I've made http://neoevents.googlecode.com to handle this kind of annotation based event handler.
#actionPerformed
private void onClick() {
//do something
}
protected void initComponents() {
JButton button = new JButton("Click me!!!");
button.addActionListener(new ActionListener(this) );
}
It looks as simple as I was expecting it to be. Annotations are available for every single listener in J2SE.
Don't mistake complicated for clever. It seems to me that this would be:
A nightmare to debug
Difficult to follow (from a maintenance perspective, or someone attempting to change something 6 months down the line)
Full of if (event instanceof NodeCreatedEvent) like code. Why this is better than subclassing an adapter I have no idea!
The main problem I see here are the method parameters, which restrict which methods can actually be used for which events, and there's no compile-time help for that.
This is what makes interfaces attractive to me for observer pattern implementations like the Java event model. Tools like eclipse can autogen method stubs so you can't get the signatures wrong. In your example, it's very easy to use the wrong parameter type and never know it until an event occurs (which might be an error case several months down the line)
One thing you might try are my annotations & processor for implementing observers and null object implementations. Suppose you have
package a.b.c;
public interface SomeListener {
void fee();
void fie();
void fo();
void fum();
}
and wanted to create a listener instance. You could write
package x.y.z;
import a.b.c.SomeListener;
import com.javadude.annotation.Bean;
import com.javadude.annotation.NullObject;
#Bean(nullObjectImplementations = {#NullObject(type = SomeListener.class) })
public class Foo extends FooGen implements SomeListener {
#Override
public void fie() {
// whatever code you need here
}
}
To create a source for these events, you can write
package a.b.c;
import com.javadude.annotation.Bean;
import com.javadude.annotation.Observer;
#Bean(observers = {#Observer(type = SomeListener.class)})
public class Source extends SourceGen {
// SourceGen will have add/remove listener and fire methods
// for each method in SomeListener
}
See http://code.google.com/p/javadude/wiki/Annotations if you're interested. Might give you some other ideas as well.
Google Guava v11 has added an EventBus component that uses this style. They also explain why they decided to use annotations rather than interfaces.
I've been thinking about a generic annotation-driven event framework as well. I like the benefits provided by static typing, but the current interface-driven event model is painful to use (ugly code). Would it be possible to use a custom annotation processor to do some compile-time checking? That might help add some of the missing "safety" that we've all grown used to.
A lot of the error checking can also be done at the time that the listeners are "registered" with the event producers. Thus, the application would fail early (when the listeners are registered), possibly even at at startup-time.
Here's an example of what the generic framework I've been toying with might look like:
public class ExampleProducer {
private EventSupport<ActionEvent> eventSupport;
public ExampleProducer() {
eventSupport = new EventSupport<ActionEvent>(this);
}
#AddListenersFor(ActionEvent.class)
public void addActionListener(Object listener)
{
eventSupport.addListener(listener);
}
#RemoveListenersFor(ActionEvent.class)
public void removeActionListener(Object listener)
{
eventSupport.removeListener(listener);
}
public void buttonClicked() {
eventSupport.fire(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, "Click"));
}
}
The producer uses EventSupport, which uses reflection to invoke the events. As mentioned before, EventSupport could preform some initial checks when the events listeners are registered.
public class ExampleListener
{
private ExampleProducer submitButton;
public ExampleListener()
{
submitButton = new ExampleProducer();
EventSupport.autoRegisterEvents(this);
}
#HandlesEventFor("submitButton")
public void handleSubmitButtonClick(ActionEvent event)
{
//...some code to handle the event here
}
}
Here, EventSupport has a static method that uses reflection to auto-register the listener with the event producer. This eliminates the need to manually register with the event source. A custom annotation processor could be used to validate that the #HandlesEventFor annotation refers to an actual field of the ExampleListener. The annotation processor could do other checks as well, such as ensuring that the event handler method signature matches up with one of the registration methods on the ExampleProducer (basically, the same check that could be performed at registration-time).
What do you think? Is this worth putting some time into fully developing?
Here's a similar project called SJES.
public class SomeController {
private Calculator c1 = new Calculator();
private Calculator c2 = new Calculator();
public SomeController() {
c1.registerReceiver(this);
c2.registerReceiver(this);
c1.add(10, 10);
c2.add(20, 20);
}
#EventReceiver(handleFor="c1")
public void onResultC1(Calculator.Event e) {
System.out.println("Calculator 1 got: " + e.result);
}
#EventReceiver(handleFor="c2")
public void onResultC2(Calculator.Event e) {
System.out.println("Calculator 2 got: " + e.result);
}
#EventReceiver
public void onResultAll(Calculator.Event e) {
System.out.println("Calculator got: " + e.result);
}
}
public class Calculator {
private EventHelper eventHelper = new EventHelper(this);
public class Event {
long result;
public Event(long result) {
this.result = result;
}
}
public class AddEvent extends Event {
public AddEvent(long result) {
super(result);
}
}
public class SubEvent extends Event {
public SubEvent(long result) {
super(result);
}
}
public void unregisterReceiver(Object o) {
eventHelper.unregisterReceiver(o);
}
public void registerReceiver(Object o) {
eventHelper.registerReceiver(o);
}
public void add(long a, long b) {
eventHelper.fireEvent(new AddEvent(a + b));
}
public void sub(long a, long b) {
eventHelper.fireEvent(new SubEvent(a - b));
}
public void pass(long a) {
eventHelper.fireEvent(new Event(a));
}
}
I think this is very easy to use.
You can also check out MBassador It is annotation driven, very light-weight and uses weak references (thus easy to integrate in environments where objects lifecycle management is done by a framework like spring or guice or somethign).
It provides an object filtering mechanism (thus you could subscribe to NodeEvent and attach some filters to restrict message handling to a set of specific types only).
You can also define your own annotations to have customized declaration of your handlers.
And it's very fast and resource efficient. Check out this benchmark showing a performance graph for different scenarios using Guava or mbassador.