如何从后台服务调用活动方法?

时间:2015-02-19 06:00:56

标签: android android-service android-actionbaractivity

我想通过从后台服务收到新数据来更新我的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 个答案:

答案 0 :(得分:0)

您应该使用LocalBroadcastReceiver

注册接收onResume中的更新并在onPause中取消注册。

答案 1 :(得分:0)

您可以使用广播接收器从服务更新UI。

在你的活动的onCreate()中注册广播接收器:

private UpdateReceiver updateReceiver;
 if (UpdateReceiver == null) 
 {
     updateReceiver = new UpdateReceiver();
     IntentFilter intentFilter = new  
                     IntentFilter("REFRESH_DATA");    
     registerReceiver(updateReceiver, intentFilter);
 }

取消注册你的活动

的onDestroy()
if (updateReceiver != null) unregisterReceiver(updateReceiver);

在你的活动中定义广播接收器:

private class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("REFRESH_DATA")) {
      //update adapter from here
    }
  }
} 

在您希望更新适配器的情况下,请调用sendBroadcast。像:

Intent intent=new Intent("REFRESH_DATA");
//u can pass the data through putExtras
sendBroadcast(intent);

答案 2 :(得分:0)

使用广播接收器从服务更新UI并在你要接收的主要活动的onCreate()中注册广播接收器

代码将在下面

private UpdateReceiver updateReceiver;
 if (UpdateReceiver == null) 
 {
     updateReceiver = new UpdateReceiver();
     IntentFilter intentFilter = new  
                     IntentFilter("REFRESH_DATA");    
     registerReceiver(updateReceiver, intentFilter);
 }

并创建类以检查更新是否已收到

    private class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("REFRESH_DATA")) {
      //update adapter from here
    }
  }
} 

答案 3 :(得分:-1)

在您的活动中注册BroadcastReceiver。在此接收器的onReceive方法中调用该方法。从您的Service sendBroadcast到此接收器,请记住将所需数据添加到您的意图中,并从onReceive方法意图中获取数据。