Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 创建AnalyticsApplication的新实例时引发ClassCastException_Java_Android_Google Analytics - Fatal编程技术网

Java 创建AnalyticsApplication的新实例时引发ClassCastException

Java 创建AnalyticsApplication的新实例时引发ClassCastException,java,android,google-analytics,Java,Android,Google Analytics,我正在尝试将谷歌分析应用到我的Android应用程序中。我遵循了这里的教程: 我复制了AnalyticsApplication子类的源代码,并将其粘贴到一个新的java类中。我将包名更改为我自己的,并在第41行将我的跟踪ID的名称设置为newTracker方法的参数。然后,在MainActivityactivity中,我在第33行和第36行添加了一个日志标记和一个跟踪器变量。在第161-173行中,我覆盖了onResume方法,并设置了一些日志信息和数据以发送给Google Analytics

我正在尝试将谷歌分析应用到我的Android应用程序中。我遵循了这里的教程:

我复制了AnalyticsApplication子类的源代码,并将其粘贴到一个新的java类中。我将包名更改为我自己的,并在第41行将我的跟踪ID的名称设置为newTracker方法的参数。然后,在MainActivityactivity中,我在第33行和第36行添加了一个日志标记和一个跟踪器变量。在第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;
    }
}
以下是主要活动:

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());
    }
}
package com.lawrence.daniel.usbidentifier;
导入android.app.ListActivity;
导入android.app.pendingent;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.hardware.usb.UsbAccessory;
导入android.hardware.usb.UsbManager;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.ArrayAdapter;
导入android.widget.ListView;
导入android.widget.Toast;
导入com.google.android.gms.analytics.HitBuilders;
导入com.google.android.gms.analytics.Tracker;
/**
*@作者丹尼尔·劳伦斯
*
*USB标识符标识USB设备并返回
*其说明、制造商、型号、序列号、,
*版本和哈希代码。
*
*版本1.0
*/
公共类MainActivity扩展了ListActivity{
//用于调试的标记。
私有静态最终字符串TAG=“MainActivity”;
//用于跟踪应用程序事件的变量。
私人追踪器;
/*
*源于Android文档。
*API指南-->连接-->附件
*/
//声明用于稍后存储附件信息值的数组。
静态最终字符串[]附件信息=新字符串[5];
私有静态最终字符串操作\u USB\u权限=
“com.lawrence.daniel.USB_许可”;
/*
mUsbReceiver广播接收器监听要安装的Android附件
插上电话。
V 1.1
*/
专用最终广播接收器mUsbReceiver=新广播接收器(){
/**
*如果USB设备和Android设备之间建立了连接,
*将显示一个对话框,要求用户接受或拒绝连接。
*如果连接被接受,USB设备将传送信息
*到Android设备。
*
*@param context应用程序上下文。
*@param意图
*
*版本1.0
*/
公共void onReceive(上下文、意图){
String action=intent.getAction();
/*
如果建立了连接,用户可以接受或拒绝连接。
*/
if(动作\u USB\u权限等于(动作)){
已同步(此){
USB附加附件=intent.getParcelableExtra(UsbManager.EXTRA_附件);
//如果连接被接受,两个设备将进行通信。
if(intent.getBooleanExtra(UsbManager.EXTRA_权限_授予,false)){
如果(附件!=null){
//创建用于设置通信的方法
}
}
//否则,敬酒。
否则{
Toast.makeText(MainActivity.this,
“附件许可被拒绝”,
吐司。长度(短)。show();
}
}
}
}
};
//声明一个全局UsbManager变量。
UsbManager musbanager;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建AnalyticsApplication类的新实例。
/**********************************************************
在LogCat中显示ClassCastException。
**********************************************************/
AnalyticsApplication=(AnalyticsApplication)getApplication();
mTracker=application.getDefaultTracker();
//初始化UsbManager。
mUsbManager=(UsbManager)getSystemService(Context.USB_服务);
//创建附件列表(当前实施仅允许一台设备)。
UsbAccessory[]accessoryList=mUsbManager.getAccessoryList();
//实例化挂起的意图对象,以便在连接设备时进行广播。
pendingent mPermissionIntent=pendingent.getBroadcast(this,0,新意图(操作权限),0);
//实例化IntentFilter对象。
IntentFilter permissionFilter=新的IntentFilter(操作\u USB\u权限);
试一试{
/*
V 1.3
*/
//将名为mUsbReceiver的广播接收器注册到适当的IntentFilter。
注册接收者(mUsbReceiver,许可过滤器);
//显示一个对话框,供用户接受或拒绝连接。
mUsbManager.requestPermission(accessoryList[0],mPermissionIntent);
//调用openAccessory方法以打开与附件的通信。
mUsbManager.openAccessory(accessoryList[0]);
//用附件信息填充附件信息数组,以便填充列表视图。
附件信息[0]=附件列表[0]。getDescription();
附件信息[1]=附件列表[0]。getManufacturer();
附件信息[2]=附件列表[0]。getModel();
附件信息[3]=附件列表[0]。getSerial();
附件信息[4]=附件列表[0]。getVersion();
//用附件的信息填充列表视图。
setListAdapter(新阵列适配器)(MainActivity.this,
android.R.layout.simple_list_item_1,附件_INFO));
getListView().setChoiceMode(Lis