Android “系统服务在 onCreate() 之前不适用于活动”错误消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11645906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:21:18  来源:igfitidea点击:

"System services not available to Activities before onCreate()" Error message?

androidmethodsoncreate

提问by Igal

When the user hits an icon in my app, I want the app first to check if the device is connected to the internet and then do something depending on the result it receives (for know it's just popping up a dialog, informing whether the device is connected or not). So I wrote this code:

当用户点击我的应用程序中的图标时,我希望应用程序首先检查设备是否已连接到互联网,然后根据它收到的结果做一些事情(知道它只是弹出一个对话框,通知设备是否已连接到互联网)连接与否)。所以我写了这段代码:

public class MainActivity extends Activity {

// SOME CONSTANTS WILL BE DEFINED HERE

AlertDialog.Builder builder = new AlertDialog.Builder(this);

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

    findViewById(R.id.icoMyIcon).setOnClickListener(listener);
}


private OnClickListener listener = new OnClickListener() {

    public void onClick(View v) {
        if (isNetworkConnected()) {
            builder.setMessage("Internet connected!").setCancelable(false)
            .setPositiveButton("OK", null);
            builder.create().show();
        } else {
            builder.setMessage("Internet isn\'t connected!")
            .setCancelable(false)
            .setPositiveButton("OK", null);
            builder.create().show();
        }

    }
};


// Check if the device is connected to the Internet
private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni == null) {
        // There are no active networks.
        return false;
    } else
        return true;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

When I'm trying to run this App on the emulator it keeps crushing and I'm getting this Error messages in LogCat:

当我尝试在模拟器上运行此应用程序时,它一直在崩溃,我在 LogCat 中收到此错误消息:

07-24 22:59:45.034: E/AndroidRuntime(894): FATAL EXCEPTION: main
07-24 22:59:45.034: E/AndroidRuntime(894): java.lang.RuntimeException: Unable to 
    instantiate activity ComponentInfo{com.my.app/com.my.app.MainActivity}: 
    java.lang.IllegalStateException: System services not available to Activities before onCreate()
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.ActivityThread.access00(ActivityThread.java:125)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.os.Looper.loop(Looper.java:123)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.ActivityThread.main(ActivityThread.java:4627)
07-24 22:59:45.034: E/AndroidRuntime(894):  at java.lang.reflect.Method.invokeNative(Native Method)
07-24 22:59:45.034: E/AndroidRuntime(894):  at java.lang.reflect.Method.invoke(Method.java:521)
07-24 22:59:45.034: E/AndroidRuntime(894):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-24 22:59:45.034: E/AndroidRuntime(894):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-24 22:59:45.034: E/AndroidRuntime(894):  at dalvik.system.NativeStart.main(Native Method)
07-24 22:59:45.034: E/AndroidRuntime(894): Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.Activity.getSystemService(Activity.java:3526)
07-24 22:59:45.034: E/AndroidRuntime(894):  at com.android.internal.app.AlertController$AlertParams.<init>(AlertController.java:743)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.AlertDialog$Builder.<init>(AlertDialog.java:273)
07-24 22:59:45.034: E/AndroidRuntime(894):  at com.my.app.MainActivity.<init>(MainActivity.java:24)
07-24 22:59:45.034: E/AndroidRuntime(894):  at java.lang.Class.newInstanceImpl(Native Method)
07-24 22:59:45.034: E/AndroidRuntime(894):  at java.lang.Class.newInstance(Class.java:1429)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-24 22:59:45.034: E/AndroidRuntime(894):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
07-24 22:59:45.034: E/AndroidRuntime(894):  ... 11 more

Why is it happening and how do I fix it? I'm a novice at this, so... please be gentle! :)

为什么会发生这种情况,我该如何解决?我是新手,所以...请温柔点!:)

回答by Jon Taylor

I think it's because your instantiating an onClick listener before on create is called. Try instantiating the onClick listener inside the onCreate()method.

我认为这是因为您在创建之前实例化了一个 onClick 侦听器。尝试在onCreate()方法内实例化 onClick 侦听器。

This may or may not be the case with the AlertDialogtoo, but I'm not entirely sure.

这也可能是也可能不是AlertDialog,但我不完全确定。

Technically I believe it is the following line that causes the problem:

从技术上讲,我认为是以下几行导致了问题:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

However, because this is being called within the isNetworkConnected()method which in turn is called within your onClick method, moving the instantiation of the onClick fixes the problem.

但是,因为这是在isNetworkConnected()方法中调用的,而方法又在您的 onClick 方法中调用,所以移动 onClick 的实例化解决了这个问题。

The clue is in the exception System services not available to Activities before onCreate()

线索是在onCreate() 之前对活动不可用的异常系统服务

回答by jeet

Error is due to create this object creation.

错误是由于创建此对象创建的。

AlertDialog.Builder builder = new AlertDialog.Builder(this);

you should do this after onCreate has been invoked.

您应该在调用 onCreate 之后执行此操作。

回答by sandy

Correct answer is

正确答案是

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

which is already mentioned by jeet and reason is you have initialized AlertDialog before any lifecycle method of activity executed with Activity context that is logically not correct.

jeet 已经提到过,原因是您在使用逻辑上不正确的 Activity 上下文执行的任何生命周期方法之前初始化了 AlertDialog。

And solution to your problem is

你的问题的解决方案是

private OnClickListener listener = new OnClickListener() {

私有 OnClickListener 监听器 = 新 OnClickListener() {

public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
    if (isNetworkConnected()) {
        builder.setMessage("Internet connected!").setCancelable(false)
        .setPositiveButton("OK", null);
        builder.create().show();
    } else {
        builder.setMessage("Internet isn\'t connected!")
        .setCancelable(false)
        .setPositiveButton("OK", null);
        builder.create().show();
    }

}

};

};

Initialize alert dialog when it need to visible. Reason behind posting answer to this old thread is the accepted answer and Jeet's answer did not solve the issue even if you move your onclick listener out of onCreate() still issue will be same.

当需要可见时初始化警报对话框。发布对此旧线程的答案的原因是已接受的答案,即使您将 onclick 侦听器从 onCreate() 中移出,Jeet 的答案也没有解决问题,问题仍然相同。

Today I came across same issue with kotlin where if internet not availbe then show error dialog and my silly mistake was

今天我遇到了与 kotlin 相同的问题,如果互联网不可用,则显示错误对话框,而我的愚蠢错误是

instead of passing context as "this" I passed it as MainActivity()

我没有将上下文作为“this”传递,而是将其作为 MainActivity() 传递

Correct R.string.error.errorDialog(this) //

Wrong R.string.error.errorDialog(MainActivity())

正确的 R.string.error.errorDialog(this) //

错误的 R.string.error.errorDialog(MainActivity())

回答by E J Chathuranga

To call system services we have to use running activity. That means we need executed onCreatemethod that inherited to the super. So to identify that we have to use the current application context to call system service.

要调用系统服务,我们必须使用运行活动。这意味着我们需要onCreate继承到super. 所以要确定我们必须使用当前的应用程序上下文来调用系统服务。

use

ConnectivityManager cm = (ConnectivityManager) getBaseContext().getSystemService(Context.CONNECTIVITY_SERVICE);

or if we have contextobject that reference to Context, we can use it as below

或者如果我们有context引用 的对象Context,我们可以如下使用它

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

回答by Alexa289

in my case, I got error message : “System services not available to Activities before onCreate()”

就我而言,我收到错误消息:“系统服务在 onCreate() 之前不可用于活动”

when I initialize class property using context like below

当我使用如下上下文初始化类属性时

 class MainActivity : AppCompatActivity() {

        // this line below
        private val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(this) 

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }

    }

回答by Jitesh Dalsaniya

add the following permission to AndroidManifest.xmlfile.

将以下权限添加到AndroidManifest.xml文件中。

i think you forget to add this permission.

我想你忘记添加这个权限了。

android.permission.ACCESS_NETWORK_STATE

it will help you.

它会帮助你。

回答by Burhan ARAS

The problem is that you define "listener" as a global variable. Since it's given in the error message: System services not available to Activities before onCreate().

问题是您将“侦听器”定义为全局变量。由于它在错误消息中给出:系统服务在 onCreate() 之前不可用于活动。

Your onCreate method should be like this:

你的 onCreate 方法应该是这样的:

private OnClickListener listener = null;

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

    listener = new OnClickListener() {

    public void onClick(View v) {
        if (isNetworkConnected()) {
            builder.setMessage("Internet connected!").setCancelable(false)
            .setPositiveButton("OK", null);
            builder.create().show();
        } else {
            builder.setMessage("Internet isn\'t connected!")
            .setCancelable(false)
            .setPositiveButton("OK", null);
            builder.create().show();
        }

    }
};


    findViewById(R.id.icoMyIcon).setOnClickListener(listener);

}

回答by Narayana J

Also, if there's an inner class, say class MyAdapter extends ArrayAdapter<myModel>or similar, it helps NOTto instantiate it - (MyAdapter = new mAdapter<mModel>()) beforethe activity's onCreate().

此外,如果有一个内部类,说class MyAdapter extends ArrayAdapter<myModel>或类似,它可以帮助进行实例化- ( MyAdapter = new mAdapter<mModel>()之前活动的onCreate()