I added the application to the Manifest and extended the class but something like onCreate won't get used in the class.
I don't know what I am doing wrong. Am I missing something? Isn't that all you should do for an application class you use?
Any help is much appreciated. I will probably just begin a new project instead and copy over the code.Manifest:
<application
android:name="MyApplication"
android:allowBackup="true"
android:icon="#drawable/smalllogo"
android:label="#string/app_name"
>
Class:
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
public class MyApplication extends Application {
Tracker tracker;
synchronized public Tracker getDefaultTracker() {
if (tracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
analytics.setLocalDispatchPeriod(1800);
tracker = analytics.newTracker();
tracker.enableExceptionReporting(true);
tracker.enableAdvertisingIdCollection(true);
tracker.enableAutoActivityTracking(true);
}
return tracker;
}
}
And it is telling me getDefaultTracker() is never used...
All right, I feel really stupid. I have to access this method from another class it isn't automatically used. So I just called on it from another class and it works. Thank you all
Related
I am trying to make a plugin and for some reason my onBlockPlace event does not work. Here is my code:
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
public class test implements Listener {
#EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
System.out.println("Test!");
player.sendMessage("Test");
}
}
Am I missing something? Please help.
It looks like you already have all the stuff necessary in the listener class. So in your plugin class (the class that extends JavaPlugin) you'll want to use this function. I'll explain the steps but it'll be a mess so you can understand what the code is doing.
Create a new instance of your listener using Listener listener = new test();
Get the server's plugin manager
PluginManager manager = getServer.getPluginManager();
Register the listener with the plugin manager manager.registerEvents(listener, this);
My codenameone application crashes anything I use this native code
package com.mycompany.interfaces;
import android.app.Application;
import android.content.Context;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
public class InitialiseApp extends Application{
private static Context context;
public static Context getContext() {
return context;
}
#Override
public void onCreate()
{
super.onCreate();
context = getApplicationContext();
try
{
FirebaseApp.initializeApp(this, new FirebaseOptions.Builder().
setApiKey("XXXXXXXXXXXXXX").
setApplicationId("XXXXXXXX").
setGcmSenderId("XXXXXXXXXX")
.build());
FirebaseInstanceId.getInstance().deleteInstanceId();
FirebaseInstanceId.getInstance().getToken("XXXXXXXXXX",FirebaseMessaging.INSTANCE_ID_SCOPE);
FirebaseMessaging.getInstance().subscribeToTopic("test");
}
catch(Exception c)
{
c.printStackTrace();
}
}
}
I declare the class in the android.xapplication_attr android:name="com.mycompany.interfaces.InitialiseApp"
Need a assistance
Are you putting this in the native interface stub or in the CN1 part of the code?
Also, I don’t think that’s how you get a context in CN1. Look in the developer guide and video tutorials for Native Interfaces. I also recall a series of blog posts about native interfaces that dive into writing the Android code. You’ll need to use something from the AndroidNativeUtil class like: AndroidNativeUtil.getActivity().
I'm a bit new to developing for android, but I feel like I've scoured quite a few forums and tried everything I can find, to no avail.
At any rate, I'm trying to build an Android plugin for my Unity project, and essentially I'd like to start an Android service from Unity. It seems as though I have all my ducks in a row, but when it goes to start the service, I get the following error message on the Android Monitor LogCat:
Unable to start service Intent{ cmd=com.activetime.androidplugin/.services.StepsService } U=0; not found
My suspicion is that the "/" between "androidplugin" and ".services" isn't suppose to be there, which is why it can't find the service, but I can't for the life of me figure out why it's there. I've seen other similar issues out there but none of the solutions seem to work; perhaps there's some issue with merging manifests?
In any case, here's the Java class from Android Studio:
private static DBReader instance;
public DBReader(){
this.instance = this;
}
public static DBReader instance(){
if(instance == null){
instance = new DBReader();
}
return instance;
}
public void startStepsService(Activity unityActivity){
unityActivity.startService(new Intent(unityActivity, StepsService.class));
}
}
And then the C# in Unity:
void Start(){
#if UNITY_ANDROID
using(AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
activityContext = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
}
using(AndroidJavaClass pluginClass = new AndroidJavaClass("com.activetime.androidplugin.DBReader")) {
if(pluginClass != null) {
databaseplugin = pluginClass.CallStatic<AndroidJavaObject>("instance");
databaseplugin.Call("startStepsService", activityContext);
}
}
#endif
}
And finally my Android Studio XML manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.activetime.androidplugin">
<application android:allowBackup="true" android:label="#string/app_name"
android:supportsRtl="true">
<service
android:name="com.activetime.androidplugin.services.StepsService">
</service>
</application>
I have two Activity classes. Activity A and Activity B. Later on I added Activity C which gets launched when user shakes the device being on Activity A or Activity B. Now if I register the ShakeListener in the Activity A and Acitivity B, I can achieve my goal
But what I want now, is a different thing, I do not want to change Activity A and Activity B. I want to write a different class, which runs for the whole app, and registers the ShakeListener for all the activities in the app. How can I do that? What kind of class should that be?
I tried extending BroadcastReceiver and registering the ShakeListener in the onReceive method, but used BOOT_EVENT which gets fired only when the device boots and not the starting of the application. So could not achieve my goal.
Then I was suggested by an SO user, to extend the Application class and registering the listener there. Now the listener gets registered, but now I need the currently running Activity and context to be passed to the Activity C. Here I'm back to zero again, because I don't want to add code in the Activity A or B. Also, AFAIK, the Application class is called before any of the Activity gets initiated, so is it possible to get the currently running Activity in the foreground?
Then I thought to move the code to find the activity in the Listener itself. Here also I needed to get the current activity and context. The context was the application context and then I tried to access all the currently open activities, following this thread. Based on the version the code is a bit different. And this is not the recommended way and gives me error.
This is the class:
package com.something.someotherthing;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Build;
import android.util.Log;
import java.lang.reflect.Field;
import java.util.List;
/**
* Created by Inquisitive on 20/5/15.
*/
public class ShakeEventListener implements SensorEventListener {
private Context context;
private Activity activity;
private String[] getPreLollipop() {
try {
#SuppressWarnings("deprecation")
List<ActivityManager.RunningTaskInfo> tasks =
activityManager().getRunningTasks(1);
ActivityManager.RunningTaskInfo currentTask = tasks.get(0);
ComponentName currentActivity = currentTask.topActivity;
return new String[]{currentActivity.getClassName()};
}
catch(Exception e){
Log.d("version","Exception" +e.getClass());
String str[]= {"abc","def"};
return str;
}
}
private String[] getLollipop() {
final int PROCESS_STATE_TOP = 2;
try {
Field processStateField = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
List<ActivityManager.RunningAppProcessInfo> processes =
activityManager().getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo process : processes) {
if (
// Filters out most non-activity processes
process.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
&&
// Filters out processes that are just being
// _used_ by the process with the activity
process.importanceReasonCode == 0
) {
int state = processStateField.getInt(process);
if (state == PROCESS_STATE_TOP)
/*
If multiple candidate processes can get here,
it's most likely that apps are being switched.
The first one provided by the OS seems to be
the one being switched to, so we stop here.
*/
return process.pkgList;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return new String[] { };
}
private ActivityManager activityManager() {
return (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
}
public String[] get() {
if (Build.VERSION.SDK_INT < 21) {
Log.d("Version","Pre-lollipop");
for(String str:getPreLollipop())
Log.d("Version",str);
return getPreLollipop();
}
else {
Log.d("Version","Lollipop");
for(String str:getLollipop())
Log.d("Version",str);
return getLollipop();
}
}
public ShakeEventListener(Context context){
Log.d("ACCELEROMETER","inside the constructor of shake event listener");
this.context=context;
String str[] = get();
try {
Class<?> myClass = Class.forName(str[0]);
activity = (Activity) myClass.newInstance();
}catch(Exception e){
//do something
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy){
}
public void onSensorChanged(SensorEvent se){
Log.d("SENSOR","On sensor changed");
//need the activity and context here..
}
}
When I try with a device having version below lollipop. It catches the SecurityException. With a device having version above lollipop, it gives the package name of my application, but not the particular class.
1 what is the correct way to achieve my goal? Whatever approach I'm following is correct? in that case, I will try to debug the code to find activity
2 If not, what are the other alternatives by which I can achieve my goal of having a global listener that listens from any activity within the app.
3 Is it achievable at all, without changing the activities?
Please help.
In your case, you need to implement a Service to listen to sensors in the background. Go through documentation:Service
You cannot just use Broadcastreceiver to accomplish this task.
Reference:
Android sensor listening when app in background
Refer this link for help:
http://code.tutsplus.com/tutorials/android-barometer-logger-acquiring-sensor-data--mobile-10558
Create a main activity class which will be extended by Activity A, B and C.
You can register your ShakeListener in this main activity.
You can define your own ActivityStack in Application class, properly manage by adding and removing activities. Finally refer to this stack from activity C.
There is example how ActivityStack works:
Back Stack Example
Im having some trouble setting up Google Analytics on my Android app. Could any one help me out and point me to some sample code or tutorial. Im trying to follow this one
Heres my code:
package com.examp2.testq;
import java.util.HashMap;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public enum TrackerName {
APP_TRACKER, // Tracker used only in this app.
}
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
:
mTrackers.put(trackerId, t);
}
return mTrackers.get(trackerId);
}
Im not sure what to do with the PROPERTY ID or how to call it?
Thanks!
Put the following line inside MainActivity:
private static final String PROPERTY_ID = "UA-xxxxx-x";
private Tracker tracker;
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
replacing UA-xxxxx-x with the tracking id for your app.
I'm using Google Analytics in an app that is only one screen, so my MainActivity onCreate method looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleAnalytics.getInstance(this).newTracker(PROPERTY_ID);
GoogleAnalytics.getInstance(this).getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
tracker = getTracker(TrackerName.APP_TRACKER);
tracker.setScreenName("MainActivity");
tracker.send(new HitBuilders.AppViewBuilder().build());
setContentView(R.layout.main);
//...etc.
This is enough for a ton of useful data in Analytics.
You'll have to add the following includes:
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.analytics.GoogleAnalytics;
Don't forget to add the following permissions before the <application> tag inside the <manifest> tag of AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Google also says to add the following tag inside the <application> tag.
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Lastly, if you're using Android Studio, Google says to add the following lines to proguard-rules.txt:
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents();
}
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL;
}
-keepnames #com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
#com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}
...and also this dependency to your project's build.gradle file:
apply plugin: 'android'
...
dependencies {
compile 'com.android.support:appcompat-v7:+'
compile 'com.google.android.gms:play-services:4.3.23'
}
Property id is simply a string of the format UA-XXXXXX-Y. It is also called the tracking id, webproperty id etc. You can get this from the admin settings of Google Analytics account. Most likely you already have it.
There are basically two ways of getting a tracker. You can create it from an xml file. If you are doing that, you need to use public Tracker newTracker (int configResId)
The second method is to use public Tracker newTracker (String trackingId). In your code snippet, you are using the second method.
Try this tutorial https://developers.google.com/analytics/devguides/collection/android/v4/
and this https://developers.google.com/analytics/devguides/collection/android/v4/events
hope this helps.
Property id i the "UA-XXXXXX-Y" In admob i think, you can create this trackig ID.