如何从Background服务向android中的活动发送列表

时间:2015-02-11 14:20:57

标签: android android-asynctask android-service

我想从后台服务发送一个列表到android中的活动

public class MyService extends Service{

    private String receiverUserInfoId;
    private String loginUserInfoId;
    private String orgMsgThreadId;
    private String userName = "Vipin";
    DatabaseHelper db;
    MessageListActivity ms;
    private String userAvatarURL;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        db = new DatabaseHelper(getApplicationContext());
        Bundle extra = intent.getExtras();
        loginUserInfoId = extra.getString("LoginUserInfoId");
        receiverUserInfoId=extra.getString("UserInfoId");
        orgMsgThreadId = extra.getString("OrgMessageThreadId");
        userName=extra.getString("UserName");
        userAvatarURL=extra.getString("UserAvatarURL");


        new syncMessageFromServer().execute();
        new SyncPendingMessageToServer();


        return super.onStartCommand(intent, flags, startId);
    }
private class syncMessageFromServer extends AsyncTask<Void, Integer, String> {

        @Override
        protected void onPreExecute() {
            // setting progress bar to zero
            //progressBar.setProgress(0);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {

        }

        @Override
        protected String doInBackground(Void... params) {
            return uploadFile();
        }

        @SuppressWarnings("deprecation")
        private String uploadFile() {
            String str = "";
            HttpResponse response;
            HttpClient myClient = new DefaultHttpClient();
            HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/GetMessage?loginUserInfoId=" + loginUserInfoId + "&recieverUserInfoId=" + receiverUserInfoId + "&isPendingToSynce=" + true);

            try {
                response = myClient.execute(myConnection);
                str = EntityUtils.toString(response.getEntity(), "UTF-8");

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                JSONArray jArray = new JSONArray(str);
                for (int i = 0; i <= jArray.length() - 1; i++) {
                    JSONObject row = jArray.getJSONObject(i);
                    ChatMessage cm = new ChatMessage();

                    cm.setOriginalMsgThreadId(row.getString("MessageThreadId"));
                    cm.setSenderUserInfoId(row.getString("SenderUserId"));
                    cm.setReceiverUserInfoId(row.getString("MultipleReceiversId"));
                    cm.setMessageStatus("SENT");
                    cm.setIsPending(0);
                    cm.setMessageText(row.getString("MessageText"));
                    cm.setMediaURL(offlineFileURL);
                    cm.setThumbImage(offlineFileURL);
                    cm.setMediaMIMEType("");
                    cm.setMediaSize(0);
                    cm.setMediaName("");
                    cm.setLatitude("");
                    cm.setLongitude("");
                    cm.setSendTimeStamp(row.getString("SendTime"));
                    cm.setReceiveTimeStamp(row.getString("ReadTime"));
                    long messageThreadId = db.SendMessage(cm);

                  MessageListActivity mLA = new MessageListActivity();
                  mLA.SetListData(cm);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return str;

        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new syncMessageFromServer().execute();

        }
    }
}

我想将ChatMessage发送到MessageListActivity类中的SetListData()函数,我该怎么做呢。只是我想刷新我的列表适配器到服务器提取的新消息

1 个答案:

答案 0 :(得分:3)

如果您想与活动进行通信,则需要使用信使。像这样更改您的服务:

public class MyService extends Service{
    public static int MESSENGER = 1;
    public static int JSONARRAY = 2;
    private String receiverUserInfoId;
    private String loginUserInfoId;
    private String orgMsgThreadId;
    private String userName = "Vipin";
    DatabaseHelper db;
    MessageListActivity ms;
    private String userAvatarURL;
    Messenger messageActivity;
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what){
             case MESSENGER:
                  messageActivity = msg.replyTo;
                  break;
        }
    }    

    @Override
public IBinder onBind(Intent intent) {
    return mMessenger.getBinder();
}

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        db = new DatabaseHelper(getApplicationContext());
        Bundle extra = intent.getExtras();
        loginUserInfoId = extra.getString("LoginUserInfoId");
        receiverUserInfoId=extra.getString("UserInfoId");
        orgMsgThreadId = extra.getString("OrgMessageThreadId");
        userName=extra.getString("UserName");
        userAvatarURL=extra.getString("UserAvatarURL");


        new syncMessageFromServer().execute();
        new SyncPendingMessageToServer();


        return super.onStartCommand(intent, flags, startId);
    }
private class syncMessageFromServer extends AsyncTask<Void, Integer, String> {

        @Override
        protected void onPreExecute() {
            // setting progress bar to zero
            //progressBar.setProgress(0);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {

        }

        @Override
        protected String doInBackground(Void... params) {
            return uploadFile();
        }

        @SuppressWarnings("deprecation")
        private String uploadFile() {
            String str = "";
            HttpResponse response;
            HttpClient myClient = new DefaultHttpClient();
            HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/GetMessage?loginUserInfoId=" + loginUserInfoId + "&recieverUserInfoId=" + receiverUserInfoId + "&isPendingToSynce=" + true);

            try {
                response = myClient.execute(myConnection);
                str = EntityUtils.toString(response.getEntity(), "UTF-8");

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                JSONArray jArray = new JSONArray(str);
                messageActivity.send(Message.obtain(null, JSONARRAY, jArray.toString()));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return str;

        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new syncMessageFromServer().execute();

        }
    }
}

在您的活动中添加以下方法:

public class MyListActivity extends Activity{
     public static Messenger mService = null;
     public final Messenger mMessenger = new Messenger(new IncomingHandler());
     public boolean mIsBound = false;

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

public void doBindService() {
        if (!mIsBound) {
            context.bindService(new Intent(context,
                    MyService.class), mConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
        }
    }

         private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            mService = new Messenger(service);

            try {
                Message msg = Message.obtain(null, MyService.MESSENGER);
                msg.replyTo = mMessenger;
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            mService = null;

        }
    };

class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MyService.JSONARRAY:
                    buildTheChatMessage((JsonArray)msg.obj);

                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    public void buildTheChatMessage(JsonArray arr){
           ChatMessage cm = new ChatMessage();

                    cm.setOriginalMsgThreadId(row.getString("MessageThreadId"));
                    cm.setSenderUserInfoId(row.getString("SenderUserId"));
                    cm.setReceiverUserInfoId(row.getString("MultipleReceiversId"));
                    cm.setMessageStatus("SENT");
                    cm.setIsPending(0);
                    cm.setMessageText(row.getString("MessageText"));
                    cm.setMediaURL(offlineFileURL);
                    cm.setThumbImage(offlineFileURL);
                    cm.setMediaMIMEType("");
                    cm.setMediaSize(0);
                    cm.setMediaName("");
                    cm.setLatitude("");
                    cm.setLongitude("");
                    cm.setSendTimeStamp(row.getString("SendTime"));
                    cm.setReceiveTimeStamp(row.getString("ReadTime"));
                    setListData(cm);
    }


}

这样,您的活动就会绑定到服务,您可以在它们之间进行通信。我希望您从这段代码中获得想法并实现您的需求。

Here是了解这些方法的更多信息的来源。