原生安卓继承uniapp后执行自定义的applicaiton与activity(实现双击退出按钮监听)

一、自定义application ,乱起八糟的不用管

1、MyApplication.java
public class MyApplication extends DCloudApplication {


    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init() {
        // 自己的业务实现
    }

    

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
  
}

2、修改AndroidManifest.xml

中添加(换成自己的路径)

二、自定义启动activity

1、MyPandoraEntry.java(记得换路径)

public class MyPandoraEntry extends PandoraEntry {

    @Override
    public void startActivity(Intent intent) {
        ComponentName componentName = intent.getComponent();
        String packageName = componentName.getPackageName();
        String className = componentName.getClassName();
        if(className.equals("io.dcloud.PandoraEntryActivity")){
            intent.setComponent(new ComponentName(packageName, "com.example.myapplication.MyPandoraEntryActivity"));
        }
        Log.e("mypandoraEntry", String.format("activity = %s, startActivity, activity name = %s", this, intent.getComponent().getClassName()));
        super.startActivity(intent);
    }

}

2、MyPandoraEntryActivity.java

public class MyPandoraEntryActivity extends PandoraEntryActivity {

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private static boolean isExit = false;

    //点击第二次时关闭应用
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 点击两次退出程序
     */
    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            // 双击退出程序时执行
            finish();
            // 以下两行是作为自己的退出逻辑
            getApplication().onTerminate();
            application().stopService();
            //参数用作状态码;根据惯例,非 0 的状态码表示异常终止。
            System.exit(0);
        }
    }

    public MyApplication application() {
        return (MyApplication) getApplication();
    }
}

3、修改AndroidManifest.xml

将PandoraEntry换成自己的MyPandoraEntry

将PandoraEntryActivity换成自己的MyPandoraEntryActivity

 

你可能感兴趣的:(uniapp)