Seb*_*Seb 18 java android android-intent
在我的主要活动中,我有以下代码:
EditText usernameText;
EditText passwordText;
public void sendLogin (View loginview){
Intent i = new Intent(this, NetworkService.class);
startService(i);
}
Run Code Online (Sandbox Code Playgroud)
目前,这只是向NetworkService发送一个intent,它按如下方式处理(截断):
public class NetworkService extends IntentService {
public NetworkService() {
super("NetworkService");
}
protected void onHandleIntent(Intent i) {
/* HTTP CONNECTION STUFF */
String login = URLEncoder.encode("Username", "UTF-8") + "=" + URLEncoder.encode("XXX", "UTF-8");
login += "&" + URLEncoder.encode("Password", "UTF-8") + "=" + URLEncoder.encode("XXX", "UTF-8");
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我需要弄清楚的是,如何将这些usernameText和passwordText值传递到NetworkService'XXX'中,但是NetworkService我想打算(没有双关语),让它处理来自不同地方的多个意图,一个来自登录,例如,使用登录令牌检索用户的一些信息.这是我的所有网络都将被包含的地方.我被告知这是Android应用程序中的最佳实践,以保持网络分离.
我的问题是:什么是这两个变量发送到的最佳方式NetworkService,以及如何,内onHandleIntent的NetworkService,我分开的代码只能做我要求它(登录,获取用户信息,获取位置数据等等)?
对不起,如果答案很简单,但我对应用程序编程很新.
谢谢
luu*_*uts 33
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);
}
Run Code Online (Sandbox Code Playgroud)
然后在你的IntentService中:
@Override
protected void onHandleIntent(Intent intent) {
String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
...
}
Run Code Online (Sandbox Code Playgroud)
IntentServices旨在处理发送给它的多个请求.换句话说,如果你继续使用startService(intent)intent 发送意图,你的NetworkService将继续onHandleIntent调用它的方法.在引擎盖下,它有一个意图队列,它将一直工作直到它完成.因此,如果您按照当前的方式继续发送意图,但通过这些putExtra方法设置了某些标志,那么您可以检测您的NetworkService应该做什么并采取适当的行动.例如login,在你的意图服务中设置一个boolean extra到你的意图,通过查找设置的标志intent.getBooleanExtra("login").如果是,请执行登录操作,否则查找您设置的其他标记.
1.对于发送 usernameText和passwordText以NetworkService做到这一点....
Intent i = new Intent(Your_Class_Name.this, NetworkService.class);
i.putExtra("username", usernameText.getText().toString());
i.putExtra("password", passwordText.getText().toString());
startService(i);
Run Code Online (Sandbox Code Playgroud)
2.要接收数据,NetworkService请执行此操作....
Intent intent = getIntent();
String userName = intent.getExtras().getString("username");
String password = intent.getExtras().getString("password");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31928 次 |
| 最近记录: |