Using putExtra to pass values to intent service

前端 未结 2 1231
猫巷女王i
猫巷女王i 2020-12-29 06:45

within my main activity I have the following code:

EditText usernameText;
EditText passwordText;
public void sendLogin (View loginview){
    Intent i = new I         


        
相关标签:
2条回答
  • 2020-12-29 06:59

    1. For sending usernameText and passwordText to NetworkService do this....

    Intent i = new Intent(Your_Class_Name.this, NetworkService.class);
       i.putExtra("username", usernameText.getText().toString());
       i.putExtra("password", passwordText.getText().toString());
       startService(i);
    

    2. To receive the data in NetworkService do this....

    Intent intent = getIntent();
       String userName = intent.getExtras().getString("username");
       String password = intent.getExtras().getString("password");
    
    0 讨论(0)
  • 2020-12-29 07:06
    public void sendLogin (View loginview){
        Intent i = new Intent(this, NetworkService.class);
        i.putExtra("username", usernameText.getText().toString());
        i.putExtra("password", passwordText.getText().toString());
        startService(i);
    }
    

    Then in your IntentService:

    @Override
        protected void onHandleIntent(Intent intent) {
        String username = intent.getStringExtra("username");
        String password = intent.getStringExtra("password");
        ...
    }
    

    IntentServices are designed to handle several requests sent to it. In other words, if you keep sending intents using startService(intent), your NetworkService will keep getting its onHandleIntent method called. Under the hood, it has a queue of intents that it will work through until it is finished. So if you keep sending intents the way you are currently, but with certain flags set through the putExtra methods, then you can detect what your NetworkService should do and act appropriately. e.g. set a boolean extra to your intent called login, in your intentservice look for that flag being set via intent.getBooleanExtra("login"). If true, do your login stuff, else look for other flags you set.

    0 讨论(0)
提交回复
热议问题