我正在创建一个应用程序,遇到了问题。基本上,第一次尝试打开应用程序时,它会崩溃,之后就没问题了。令人困惑的是,只有从Google Play下载应用程序时才会出现这种情况。如果我直接从Android Studio将应用程序加载到手机上,则不会出现任何错误。
java.lang.RuntimeException:
at android.app.ActivityThread.handleReceiver (ActivityThread.java:3290)
at android.app.ActivityThread.-wrap20 (ActivityThread.java)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1715)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6682)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)
Caused by: java.lang.ClassNotFoundException:
at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass (ClassLoader.java:380)
at java.lang.ClassLoader.loadClass (ClassLoader.java:312)
at android.app.ActivityThread.handleReceiver (ActivityThread.java:3285)
经过调查,我发现人们说要清除设备的缓存。这解决了问题……但这只是清除了应用程序,然后它就可以正常工作。初始安装仍会崩溃。这在多个设备上发生,但我无法在调试时重现它。我唯一的想法是在调用setContentView()之后,在onCreate()中使用了这段代码。
Intent intent = new Intent(this, NotificationListener.class);
startService(intent);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
NotificationListener.class继承了NotificationListenerService类。除了初始启动之外,一切都运作良好。
更新
以下是我在AndroidManifest中设置服务的方式:
<service android:name=".NotificationListener"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
这里是我NotificationListenerService的简化版本:
public class NotificationListener extends NotificationListenerService
{
private IBinder mBinder = new LocalBinder();
@Override
public void onNotificationPosted(StatusBarNotification sbn)
{
super.onNotificationPosted(sbn);
// custom code
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn)
{
super.onNotificationRemoved(sbn);
}
@Override
public IBinder onBind(Intent intent)
{
if (SERVICE_INTERFACE.equals(intent.getAction()))
return super.onBind(intent);
else return mBinder;
}
public class LocalBinder extends Binder
{
public NotificationListener getService()
{
return NotificationListener.this;
}
}
}
这是用于Binder的ServiceConnection:
private ServiceConnection serviceConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder)
{
NotificationListener.LocalBinder localBinder = (NotificationListener.LocalBinder) iBinder;
notificationListener = localBinder.getService();
bound = true;
// code to call custom function in NotificationListener class
}
@Override
public void onServiceDisconnected(ComponentName componentName)
{
notificationListener = null;
bound = false;
}
};
我知道这一定是服务绑定的问题,因为如果我删除所有绑定代码并只启动服务,一切都会按照预期运行。只有当我添加绑定代码时才会出现此错误。