简体   繁体   中英

Android onCreate called twice after phone reboot, makes fragment stop working

I have written an application for Android that has an issue (crash) when it is launched immediately (with in 5 seconds or so) after the phone is rebooted. Due to one reason or another, the OnCreate method is called for a second time. I thought this may have been the problem, but after researching this, I found out the android system may recall onCreate after start up as it is still starting system services - such as getting the "MCM".

In my application in the MainActivity I have a statically bound fragment that is bound through XML. The fragment has code in it that checks that location permissions were granted:

if (ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)

The problem is, this.getContext() returns null! It definitely has something to do with the fact onCreate is being called more than once, because when the phone is not booting and onCreate is only called once the application works perfectly!

Here is the only reference I make to the fragment in my onCreate method in the mainActivity :

android.support.v4.app.Fragment fragMap = getSupportFragmentManager().findFragmentById(R.id.mv_1);

    if (fragMap instanceof FragmentMap)
    {
        theMap = (FragmentMap) fragMap;
    }

Here is the fragment bound through XML :

<fragment
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:id="@+id/mv_1"
    android:name="com.sunhillo.personneltrackerv002.FragmentMap"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="64dp"/>

Thank you very much for any help you can provide! I am still new to Android programming, and am attempting to learn the ins and outs!

If your ultimate aim is to access the location permissions, simply add these permissions in manifest file. And if you wish to perform this check via java, don't add this to individual fragments. Add this syntax only to the MainActivity java file that refers to the fragments. I hope this helps. :)

您应该使用启动模式Single Task或Single top,这将避免调用多个onCreate,您应该使用getApplicationContext()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM