如何在 Java Android 上的任何任务之前运行事件?

问题描述 投票:0回答:1

我有代码并使用此代码为退出应用程序工作:

class Example extends Dialog {
    @Override
    public void dismiss() {
        super.dismiss();
        if (isForceExists != false) {
            int id = android.os.Process.myPid();
            android.os.Process.killProcess(id);
        }
    }
}

但是..当我想在退出应用程序之前运行其他事件时不起作用(跳过事件)。

class ExampleActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
       Example exDialog = new Example();
       exDialog.setDismissListener(new OnDismissListener() {
           AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
           builder.setTitle("Exit Application")
                 .setMessage("Thank you for using this application, happy nice day ^_^")
                 .show();
       });
    }
}

我想在退出应用程序之前运行事件关闭或等待进度任务,该怎么办?但它是脚本强制退出应用程序而不运行事件之前?

android events thread-synchronization android-event
1个回答
0
投票

您应该在您的Example类或ExampleActivity本身中处理事件逻辑,而不是在显示对话框时尝试在ExampleActivity的onCreate方法中运行事件。

修改您的示例类以包含解雇事件的回调:

class Example extends Dialog {
    private OnDismissListener dismissListener;

    public void setDismissListener(OnDismissListener listener) {
        this.dismissListener = listener;
    }

    @Override
    public void dismiss() {
        if (dismissListener != null) {
            dismissListener.onDismiss(this);
        }
        super.dismiss();
    }
}

修改您的ExampleActivity以实现OnDismissListener接口并重写其onDismiss方法以在退出应用程序之前执行您想要的事件:

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

public class ExampleActivity extends Activity implements DialogInterface.OnDismissListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Example exDialog = new Example(this);
        exDialog.setDismissListener(this);
        exDialog.show();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        // This method will be called before the dialog is dismissed.
        // You can perform your desired event here.
        // For example, showing a Toast message.
        Toast.makeText(this, "Before exit event executed.", Toast.LENGTH_SHORT).show();
        
        // After the event, you can exit the application if needed.
        finish();
    }
}

此方法可确保您的事件在您关闭对话框时在应用程序退出之前运行。

© www.soinside.com 2019 - 2024. All rights reserved.