How Android App generates Ethereum Wallet

Time:2020-6-10

There is a lot of work to be done to generate the Ethereum wallet for Android applications, but if we go step by step, we should also be clear:

1. Inapp/build.gradleThe following dependencies are integrated in:

compile ('org.web3j:core-android:2.2.1')

Web3j core is the core class library used to download the data of Ethereum blockchain from the server. It is often used for Ethereum development.

2. We will design an Android UI example with text editing and buttons on the screen. In EditText, the user will be asked to enter the password for the wallet. Then on the click event of the button, we will start the process of sending the password. Here is layout.xml File:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/content"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="@string/textview_password"
        android:padding="10dp"/>
    <Button
        android:id="@+id/generate_wallet_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/textview_generate_wallet"/>
</LinearLayout>

3. We will create a fileoutputstream path to save the created wallet file in the storage, which requires read-write storage permission.

4. For Android user API > 26, you need to have runtime permission to perform the above steps.

5. Then there is a nameWalletUtilsClass of. stayweb3jcoreMedium. In this class, there is a methodgenerateWalletNewFile(password, path), which will accept the password parameters and the path to the wallet file. Will be able to create wallet files.

6.web3jcoreThere is also a class credential inCredentials, it will useWalletUtils.loadCredentials(password,path)Method to load all credentials for the file. The following is a class and interface for generating wallet files:

public class EthereumGenerationPresenter implements EthereumGenerationContract.Presenter {
    private final EthereumGenerationContract.View mWalletGenerationView;
    private String mPassword;
    public EthereumGenerationPresenter(EthereumGenerationContract.View walletGenerationView, String password) {
        mWalletGenerationView = walletGenerationView;
        mPassword = password;
    }
    @Override
    public void generateWallet(final String password) {
        String fileName;
        try {
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            if (!path.exists()) {
                path.mkdir();
            }
            fileName = WalletUtils.generateLightNewWalletFile(password, new File(String.valueOf(path)));
            Log.e("TAG", "generateWallet: " + path+ "/" + fileName);
            Credentials credentials =
                    WalletUtils.loadCredentials(
                            password,
                            path + "/" + fileName);
            mWalletGenerationView.showGeneratedWallet(credentials.getAddress());
            Log.e("TAG", "generateWallet: " + credentials.getAddress() + " " + credentials.getEcKeyPair().getPublicKey());
        } catch (NoSuchAlgorithmException
                | NoSuchProviderException
                | InvalidAlgorithmParameterException
                | IOException
                | CipherException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void start() {
        generateWallet(mPassword);
    }
}

public interface EthereumGenerationContract {
    interface View extends BaseView<Presenter> {
        void showGeneratedWallet(String walletAddress);
    }
    interface Presenter extends BasePresenter {
        void generateWallet(String password);
    }
}

public interface BasePresenter {
    void start();
}

public interface BaseView<T> {
    void setPresenter(T presenter);
}

7. NowCredentialsClass will save Ethereum’s wallet address and more information about the file.

8. Now you can use the following function to get the address:

 credentials.getAddress()->

Public key

 credentials.getPublicKey()

Private key

credentials.getEcKeyPair()

9. Wallet generation classActivityAs follows:

public class WalletGenerationActivity extends AppCompatActivity implements EthereumGenerationContract.View {

    private static final int REQUEST_PERMISSION_WRITE_STORAGE = 0;

    private EthereumGenerationContract.Presenter mWalletPresenter;

    private Button mGenerateWalletButton;

    private String mWalletAddress;

    private EditText mPassword;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generation);

        mGenerateWalletButton = (Button) findViewById(R.id.generate_wallet_button);
        mPassword = (EditText) findViewById(R.id.password);

        mGenerateWalletButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int permissionCheck = ContextCompat.checkSelfPermission(WalletGenerationActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(
                            WalletGenerationActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_PERMISSION_WRITE_STORAGE);
                } else {
                    mWalletPresenter = new EthereumGenerationPresenter(WalletGenerationActivity.this,
                            mPassword.getText().toString());
                    mWalletPresenter.generateWallet(mPassword.getText().toString());
                    Intent intent = new Intent(WalletGenerationActivity.this, WalletActivity.class);
                    intent.putExtra("WalletAddress", mWalletAddress);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void setPresenter(EthereumGenerationContract.Presenter presenter) {
        mWalletPresenter = presenter;
    }

    @Override
    public void showGeneratedWallet(String address) {
        mWalletAddress = address;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_WRITE_STORAGE: {
                if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    finish();
                } else {
                    mWalletPresenter.generateWallet(mPassword.getText().toString());
                }
                break;
            }
        }
    }
}

10. The activity class with textview is used to display the wallet address.

public class WalletActivity extends AppCompatActivity {

    private TextView mWalletAddress;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet);
        mWalletAddress = (TextView) findViewById(R.id.account_address);
        Bundle extras = getIntent().getExtras();
        mWalletAddress.setText(extras.getString("WalletAddress"));
    }
}

If you want to develop java Ethereum quickly, please see our carefully crafted tutorial:
Java Ethereum development tutorial, mainly for Java and Android programmers to carry out block chain Ethereum development web3j detailed explanation.

Other Ethereum tutorials are as follows:

  • The introduction course of Ethereum mainly introduces smart contract and DAPP application development, which is suitable for introduction.
  • Advanced course of Ethereum development, mainly introducing the use of node.js , mongodb, blockchain, IPFs realize the decentralized e-commerce DAPP practice, which is suitable for advanced.
  • Python Ethereum is a detailed explanation of the development of blockchain Ethereum by Python engineers using web3.py.
  • PHP Ethereum mainly introduces the use of PHP for smart contract development interaction, account creation, transaction, transfer, token development, filters and events.
  • C ා Ethereum, mainly explains how to use C ා to develop. Net based Ethereum applications, including account management, status and transaction, smart contract development and interaction, filters and events, etc.
  • PHP bitcoin development course, for beginners, covers the core concepts of bitcoin, such as blockchain storage, decentralized consensus mechanism, key and script, transaction and utxo, etc. Meanwhile, it also explains how to integrate bitcoin support functions in PHP code, such as creating address, managing wallet, constructing naked transaction, etc., which are rare for PHP engineers Currency development learning course.
  • EOS introductory course, this course helps you quickly get started with the development of decentralized application of EOS blockchain, covering core knowledge points such as EOS tool chain, account and wallet, token issuance, smart contract development and deployment, code and smart contract interaction, etc., and finally complete the development of a memo DAPP by comprehensively using each knowledge point.

Original translation, reprint please indicate the source. Here is the original