简体   繁体   中英

How do i set a listener in an activity from another class?

I am working on an application that needs to read an incoming message. Now, i found out that i need to use the onReceive method from the BroadcastReceiver class. Now i got to know that java does not allow extending two classes, so how do i get it working, i have been stuck on this from a long time, please help! Also if there is some other way to do this, please do quote.

public class SMS extends Activity { Button btnSendSMS; EditText txtPhoneNo; EditText txtMessage;

 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sms); btnSendSMS = (Button) findViewById(R.id.btnSendSMS); txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo); btnSendSMS.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String phoneNo = txtPhoneNo.getText().toString(); if (phoneNo.length()>0) sendSMS(phoneNo, phoneNo); else Toast.makeText(getBaseContext(), "Please enter a valid Phone Number.", Toast.LENGTH_SHORT).show(); } }); } private void sendSMS(String phoneNumber, String message) { PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, SMS.class), 0); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, pi, null); } Context context = getApplicationContext(); Intent intent = new Intent(); object.onReceive(context, intent); } 

class SMSBroadcastReceiver extends BroadcastReceiver {

 private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; private static final String TAG = "SMSBroadcastReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Intent recieved: " + intent.getAction()); Toast.makeText(context, "HI", Toast.LENGTH_SHORT).show(); if (intent.getAction().equals(SMS_RECEIVED)) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[])bundle.get("pdus"); final SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]); } if (messages.length > -1) { Toast.makeText(context, "Message recieved: " + messages[0].getMessageBody(), 7000).show(); } } } } } 

You don't need to extend two classes (which is not possible and never required in java) to achieve your goal. For getting the last message simply create a static message variable, lets say in your SMSBroadcastReceiver and set that variable to latest message received in onreceive. This static variable can be accessed throughout your app using SmsReceiver.latestmessage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM