简体   繁体   中英

Android — onCreate() of extended class of MainActivity not called

At one point I included the listeners and methods for MediaPlayer in MainActivity and it worked. Then I decided MainActivity is so large that I should move the code to an extended class (or should I not use an extended class).

MainActivity

public class MainActivity extends AppCompatActivity {
    . . . 
    private muPlayer muPlay;
    . . .
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        . . .
        muPlay = new muPlayer();
        . . .
        // May be called from here or from a listener
        muPlay().play();
        . . .
    }
    protected int getLayoutId(){
        return R.layout.activity_main;
    }
}

The extended class

public class muPlayer extends MainActivity implements
        OnCompletionListener, OnClickListener {
. . .
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( getLayoutId() );

        thisPath    = thisContext.getFilesDir().getPath();
        . . .
        muToggle = (Button) this.findViewById(R.id.butToggle);
        . . .
        muToggle.setOnClickListener(this);
        muRewind.setOnClickListener(this);
        progBar.setOnClickListener(this);
        progBar.setClickable(false);
        . . .
    }
    public void onCompletion(MediaPlayer mp) {
        . . .
    }
    @Override
    public void onClick( View v ) {
        . . .
    }
    public void play( ) {
        . . .
    }
    . . . 
}

And MainActivity is identified in AndroidManifest.xml, not the muPlayer.

<application
    . . .
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

OnCreate() in muPlayer is not being called. What am I missing? Or is my whole approach wrong?

Thank you.

You have extend MainActivity in muPlayer so MainActivity is Parent Class. Call muPlayer in MainiFest

<application
. . .
<activity android:name=".muPlayer">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

You are missing to declare muPlayer in your mainfest. Add following entry in maifest:

<activity android:name=".muPlayer "/>

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