1

I make a simple Android Apps that will update its view when an SMS is received. This is the code for my receiver class

public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    intent.setClass(context, SMSReceiverService.class);
    intent.putExtra("result", getResultCode());
    WakefulIntentService.sendWakefulWork(context.getApplicationContext(), intent);
}

}

That class will call SMSReceiverService class to handle the oncoming SMS and execute method notifyMessageReceived, which is shown below.

private void notifyMessageRecevied(SMS message) {
    if(!isInMyApps()) {
                launchPopUp();
    }
    else {
        //updating view should go here
    }
}

The problem is, I don't know how to update the view in my activity (which is in separate class, not the SMSReceiverService class), when I tried to update my TextView in my activity, it thrown an CalledFromWrongThreadException. Can anybody please help me ?

Thanks in advance, and sorry about my bad English...

djargonforce
  • 259
  • 1
  • 3
  • 8

2 Answers2

3

You can create an activity variable to hold the instance of the activity you want.

In SMSReceiver (the one you want to call):

SMSReceiverService.setMainActivity(this);

In SMSReceiverService (the one you want to update from):

public static SMSReceiver smsActivity;
public static void setMainActivity(SMSReceiver activity) 
{
    smsActivity = activity;      
}

...

smsActivity.runOnUiThread(new Runnable() {
     public void run() {    
             try{
                    smsActivity.textView.setText("");
             }
             catch{}
     }
}

Assuming SMSActivity is the file that contains the view you want to update.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Brianjs
  • 2,079
  • 2
  • 20
  • 32
  • it didn't work. Correct me if i'm wrong, but the 'first file' is the activity that i want to update the view, and the 'second file' is the class which is called from the broadcast recevier or in this case, the SMSReceiverService class. Am I right ? – djargonforce Mar 07 '13 at 17:47
  • Correct you can also try adding a runOnUiThread and see if that works. Check my edit above. Make sure FirstFile is the name of the class of the view you want to update. – Brianjs Mar 07 '13 at 17:59
  • Ashok thought the same too. I'll give it a try. Thank you very much Brianjs – djargonforce Mar 07 '13 at 18:04
  • I changed the name of the variables (hopefully correctly) so that they are a little clearer. – Brianjs Mar 07 '13 at 18:08
0

Assuming the service has Context of User Activity

Activity a=(Activity)userContext;
a.runOnUiThread(/*runnable method of activity which calls UpdateView() */);
Ashok
  • 601
  • 8
  • 11
  • Ashok, I already found a solution by using handlers but your method seems better. I'll give it a try. Thanks a lot for your answer – djargonforce Mar 07 '13 at 18:02