服务IntentService以及传递服务的处理结果
@EActivity(R.layout.input_club_name) public class JoinActivity extends BaseActivity{ @ViewsById({R.id.et_input_room_roomName, R.id.et_input_room_name}) ArrayList<EditText> etlist = new ArrayList<EditText>(); @Click(R.id.btn_input_club_name_submit) public void join(){ //显示进度条 ProgressBarUtil.show(this, "正在连接服务器,请稍后..."); String roomName = etlist.get(0).getText().toString(); String Name = etlist.get(1).getText().toString(); //启动IntentService Intent intent = new Intent(this,ClubBiz.class); intent.putExtra("roomName", roomName); intent.putExtra("Name", Name); //如何将Service的结果返回给activity:发广播,PendingIntent int requestCode = 100; Intent data = new Intent(); int flags = 0; PendingIntent pendingIntent =this.createPendingResult(requestCode, data, flags); //将pendingIntent放到启动service的intent中。 intent.putExtra("pendingIntent", pendingIntent); startService(intent);//1.注册服务:<service android:name=".biz.ClubBiz" > 启动服务并传递登陆的房间和房间名 } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {//4.根据pengdIntent传递的结果做进一步的处理。 super.onActivityResult(requestCode, resultCode, data); try{ if(requestCode==100 && resultCode ==200){ int status = data.getIntExtra(Constants.KEY_STATUS, -1); if(status==Constants.STATE_OK){ ProgressBarUtil.close(); Tools.showInfo(this, "加入成功!"); startActivity(new Intent(this,ChatActivity_.class)); } if(status==Constants.STATE_FAILURE){ ProgressBarUtil.close(); Tools.showInfo(this, "加入俱乐部失败!"); } } }catch (Exception e) { ExceptionUtil.handlerException(e); } } }
服务类:
/** * IntentService能够自己创建一个线程 * @author Administrator * */ public class ClubBiz extends IntentService{ // public ClubBiz(String name) { // super(name); //改成无参构造方法 public ClubBiz() { super("ClubBiz"); } @Override protected void onHandleIntent(Intent intent) {//2.处理:根据intent中传递的房间名和昵称完成房间登陆 int status = Constants.STATE_OK; try{ String roomName = intent.getStringExtra("roomName"); String Name = intent.getStringExtra("Name"); String room=roomName + "@conference." + TApplication.serviceName; TApplication.multiUserChat = new MultiUserChat(TApplication.xmppConnection, room); TApplication.multiUserChat.join(Name); }catch (Exception e) { status = Constants.STATE_FAILURE; ExceptionUtil.handlerException(e); }finally{ try{ //用pendingintent中把service中的结果传递给service; PendingIntent pendingIntent = intent.getParcelableExtra("pendingIntent"); Intent data = new Intent(); data.putExtra(Constants.KEY_STATUS,status); pendingIntent.send(this, 200, data);//3.将处理的结果通过pendIntent返回给Activity,并触发Activity中的onActivityResult事件处理结果。 }catch (Exception e) { ExceptionUtil.handlerException(e); } } } }