[英]How do I use both CordovaActivity and AppCompatActivity in Android java code?
I'm making a Cordova plugin so I need to extend the MainActivity class with CordovaActivity.我正在制作一个 Cordova 插件,所以我需要使用 CordovaActivity 扩展 MainActivity 类。 I also need to use AppCompatActivity.
我还需要使用 AppCompatActivity。 In a native app I extended MainActivity with AppCompatActivity and everything worked fine but in my Cordova plugin I'm not able to extend twice.
在本机应用程序中,我使用 AppCompatActivity 扩展了 MainActivity 并且一切正常,但在我的 Cordova 插件中,我无法扩展两次。
I'm trying to launch some code to keep running in the background.我正在尝试启动一些代码以继续在后台运行。 When I try this within onCreate:
当我在 onCreate 中尝试此操作时:
appCompat = new AppCompatActivity();
Intent intent = new Intent(this, MyClass.class);
appCompat.startService(intent);
I define global variable:我定义了全局变量:
private AppCompatActivity appCompat;
I get an error at runtime about the context (appCompat) being null.我在运行时收到关于上下文 (appCompat) 为空的错误。 This is the actual error:
这是实际的错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Does anyone know how I can use AppCompatActivity without using it as an extension?有谁知道如何在不将其用作扩展的情况下使用 AppCompatActivity?
(edit: I've attached the whole class for the sake of clarity) (编辑:为了清楚起见,我附上了整个班级)
public class MainActivity extends CordovaActivity {
private AppCompatActivity appCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = this.getBaseContext();
Intent intent = new Intent(context, MyClass.class);
appCompat = new AppCompatActivity();
appCompat.startService(intent); // CAUSES CRASH AT RUNTIME
}
}
I updated CordovaActivty class to extend AppCompatActivity, as i had to deal with Toolbar.我更新了 CordovaActivty 类来扩展 AppCompatActivity,因为我必须处理工具栏。 I'm not sure if its the right approach, but it works fine for me.
我不确定它是否是正确的方法,但对我来说效果很好。
Well it turns out I don't need to use AppCompatActivity to run services in the background.好吧,事实证明我不需要使用 AppCompatActivity 在后台运行服务。 I can simply use:
我可以简单地使用:
Intent intent = new Intent(this, MyClass.class);
startService(intent)
and it works just fine.它工作得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.