Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...