Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

android - Can I combine my code into some kind of "global activity"?

Is there any global activity on Android such that I put my code in that one activity, and it affects all activities in my project? This occurs to me because the same code is written in multiple activities like KeyEvent.KEYCODE_BACK

For example here I use:

public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            try {
                final Intent itnt_BackServices = new Intent(this,
                        BackServices.class);
                AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
                alertbox.setTitle("Touch signs");
                alertbox.setMessage("Do you want to quit!");
                alertbox.setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface arg0, int arg1) {
                                stopService(itnt_BackServices);
                                mPlayer.stop();

                                finish();
                            }
                        });
                alertbox.setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface arg0, int arg1) {
                            }
                        });
                alertbox.show();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        return false;
    }

I copy and paste this in each activity, and I would rather use some kind of global activity.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a class that extends Activity and then extend the CustomActivity to all the Activity Class like this.

public abstract class CustomActivity extends Activity{

    public abstract void initComponents();  // you can create a abstract method
    public abstract void addListner();       // you can create a abstract method

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

         if ((keyCode == KeyEvent.KEYCODE_BACK)) {
              // your stuff here....
            }
        return true;
    }
}

Now you can extend this class where you want to extend any class with Activity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...