创建AnalyticsApplication的新实例时抛出ClassCastException

时间:2016-02-01 20:52:44

标签: java android google-analytics

我正在尝试将Google Analytics实施到我的Android应用中。我按照这里的教程:Add Analytics to Your Android App

我复制了AnalyticsApplication子类的源代码并将其粘贴到新的java类中。我将包名更改为我自己的,并在第41行设置我的跟踪ID的名称作为newTracker方法的参数。然后,在我的MainActivityactivity中,我在第33和36行添加了一个日志标记和一个Tracker变量。在第161-173行中,我重写了onResume方法并设置了一些日志信息和数据以发送到Google Analytics。

以下是AnalyticsApplication类:

/*
* Copyright Google Inc. All Rights Reserved.
*
* 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.lawrence.daniel.usbidentifier;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
import com.lawrence.daniel.usbidentifier.R;

/**
 * This is a subclass of {@link Application} used to provide shared objects for this app, such as
 * the {@link Tracker}.
 */
public class AnalyticsApplication extends Application {
    private Tracker mTracker;

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     * @return tracker
     */
    synchronized public Tracker getDefaultTracker() {         
        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
            mTracker = analytics.newTracker("UA-73160447-1");
       }
       return mTracker;
    }
}

这是MainActivity活动:

package com.lawrence.daniel.usbidentifier;

import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

/**
 * @author Daniel Lawrence
 *         <p>
 *         The USB Identifier identifies a USB device and returns
 *         its Description, Manufacturer, Model, Serial Number,
 *         Version, and Hash Code.
 *         <p>
 *         Version 1.0
 */

public class MainActivity extends ListActivity {

    // A tag for debugging.
    private static final String TAG = "MainActivity";

    // A variable to track app events.
    private Tracker mTracker;

    /*
     * Derived from Android Documentation.
     * API Guides --> Connectivity --> Accessory
     */

    // Declare an array for storing accessory information values later on.
    static final String[] ACCESSORY_INFO = new String[5];

    private static final String ACTION_USB_PERMISSION =
            "com.lawrence.daniel.USB_PERMISSION";

    /*
    The mUsbReceiver broadcast receiver listens for an Android accessory to be
plugged into the phone.

V 1.1
 */

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    /**
     * If a connection between a USB device and an Android device is made,
     * a dialog box displays, asking the user to accept or reject the connection.
     * If the connection is accepted, the USB device will communicate information
     * to the Android device.
     *
     * @param context The application context.
     * @param intent
     *
     * Version 1.0
     */

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        /*
        If a connection is made, the user can accept or reject the connection.
         */
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);

                // If the connection is accepted, both devices will communicate.
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (accessory != null) {

                        // create method to set up communication
                    }
                }

                // Otherwise, a Toast is made.
                else {
                    Toast.makeText(MainActivity.this,
                            "permission denied for accessory",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
};

// Declare a global UsbManager variable.
UsbManager mUsbManager;

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

    // Create a new instance of the AnalyticsApplication class.
    /**********************************************************
    Shows ClassCastException in LogCat.
     **********************************************************/
    AnalyticsApplication application = (AnalyticsApplication) getApplication();
    mTracker = application.getDefaultTracker();

    // Initialize the UsbManager.
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

    // Create a list of accessories attached (current implementation only allows one device).
    UsbAccessory[] accessoryList = mUsbManager.getAccessoryList();

    // Instantiate a Pending Intent object to get the broadcast made when a device is connected.
    PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

    // Instantiate an IntentFilter object.
    IntentFilter permissionFilter = new IntentFilter(ACTION_USB_PERMISSION);

    try {

        /*
        V 1.3
         */

        // Register the Broadcast Receiver named mUsbReceiver with the proper IntentFilters.
        registerReceiver(mUsbReceiver, permissionFilter);

        // Displays a dialog for the user to accept or reject the connection.
        mUsbManager.requestPermission(accessoryList[0], mPermissionIntent);

        // Call the openAccessory method to open communication with the accessory.
        mUsbManager.openAccessory(accessoryList[0]);

        // Fill the ACCESSORY_INFO array with the accessory's info so it can populate the ListView.
        ACCESSORY_INFO[0] = accessoryList[0].getDescription();
        ACCESSORY_INFO[1] = accessoryList[0].getManufacturer();
        ACCESSORY_INFO[2] = accessoryList[0].getModel();
        ACCESSORY_INFO[3] = accessoryList[0].getSerial();
        ACCESSORY_INFO[4] = accessoryList[0].getVersion();

        // Populate the ListView with the accessory's info.
        setListAdapter(new ArrayAdapter<>(MainActivity.this,
                android.R.layout.simple_list_item_1, ACCESSORY_INFO));
        getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
        getListView().setTextFilterEnabled(true);

    } catch (IllegalArgumentException | NullPointerException e) {

        // If user starts the app and there is no accessory attached, show Toast message.
        Toast.makeText(this, "no accessory detected", Toast.LENGTH_SHORT).show();
    }
}

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

    // When the onResume method is called, log that the app is setting the screen name.
    Log.i(TAG, "Setting screen name: " + this.getApplication());

    /*
    Send data to Google Analytics
     */
    mTracker.setScreenName("Image~" + this.getApplication());
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }
}

我遇到的问题是,在MainActivity的第111-112行,我正在尝试创建一个新的AnalyticsApplication类实例,并在LogCat报告中收到ClassCastException。我已经探索了几个在线论坛,发现一般的解决方案是将AnalyticsApplication类添加到AndroidManifest。但是,这并没有解决我的问题。

0 个答案:

没有答案