-1

バックグラウンド サービスから新しいデータを受信して​​更新したいので、バックグラウンドからメソッドChatMessageAdapterを呼び出してアダプターを更新します。UpdateAdapter

ここに私のServiceClass

public class MyService extends Service{

private String loginUserInfoId;
SessionManager session;
DatabaseHelper db;
MessageListActivity mLA;

long totalSize = 0;

@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());
    mLA = new MessageListActivity();

    session = new SessionManager(getApplicationContext());
    session.checkLogin();
    HashMap<String, String> user = session.getUserDetails();
    loginUserInfoId = user.get(SessionManager.KEY_USER_INFO_ID);

    if(isInternetOn()) {
        new syncMessageFromServer().execute();
        new SyncPendingMessageToServer();
    }


    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

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/GetAllMessage/" + loginUserInfoId);

        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();
                String offlineFileURL = "";

                /******* Firstly take data in model object ******/
                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"));

                mLA.UpdateAdapter(ChatMessage cm);

                long messageThreadId = db.SendMessage(cm);


            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return str;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if(isInternetOn()) {
            new syncMessageFromServer().execute();
        }

    }
}

}

これは私の MessageActivityList クラスです:

public class MessageListActivity extends ActionBarActivity {

private String receiverUserInfoId;
private String loginUserInfoId;
private String orgMsgThreadId;
private String userName;
private String uploadedFileURL = "";

DatabaseHelper db;
SessionManager session;
private ChatMessageAdapter chatMessageAdapter;

private EditText chatText;
private ImageButton buttonSend;
private ListView listView;

private static final String TAG = MessageListActivity.class.getSimpleName();


// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

private Uri fileUri; // file url to store image/video

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

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
            .detectAll()
            .penaltyLog()
            .build());

    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
            .penaltyLog()
            .build());

    db = new DatabaseHelper(getApplicationContext());

    session = new SessionManager(getApplicationContext());
    session.checkLogin();
    HashMap<String, String> user = session.getUserDetails();
    loginUserInfoId = user.get(SessionManager.KEY_USER_INFO_ID);

    Intent intent=getIntent();
    Bundle extra = intent.getExtras();
    receiverUserInfoId=extra.getString("UserInfoId");
    orgMsgThreadId = extra.getString("OrgMessageThreadId");
    userName=extra.getString("UserName");
    setTitle(userName);

    listView = (ListView) findViewById(R.id.messageList);
    chatMessageAdapter = new ChatMessageAdapter(getApplicationContext(), R.layout.activity_single_message);
    listView.setAdapter(chatMessageAdapter);

    buttonSend = (ImageButton) findViewById(R.id.buttonSend);
    chatText = (EditText) findViewById(R.id.chatText);
    chatText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                if(chatText.getText().toString().trim().length() > 0){
                    sendChatMessage();
                }

            }
            return false;
        }
    });
    buttonSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            sendChatMessage();
        }
    });

    listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    // listView.setAdapter(chatMessageAdapter);

    //to scroll the list view to bottom on data change
    chatMessageAdapter.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            listView.setSelection(chatMessageAdapter.getCount() - 1);
        }
    });
    setListData();
}

public void UpdateAdapter(ChatMessage cm) {
            chatMessageAdapter.add(cm);
    }
}

このメソッドを呼び出して、サーバーが受信したものUpdateAdapterを更新するにはどうすればよいですか?ChatMessage

4

4 に答える 4

0

LocalBroadcastReceiverを使用する必要があります。

onResume で更新を受信するために登録し、onPause で登録解除します。

于 2015-02-19T06:11:03.290 に答える
-1

アクティビティ内にBroadcastReceiverを登録します。このレシーバーのonReceiveメソッドでそのメソッドを呼び出します。Service sendBroadcastからこのレシーバーに、必要なデータをインテントに追加し、onReceive メソッドのインテントからデータをフェッチすることを忘れないでください。

于 2015-02-19T06:57:30.753 に答える