0
我正在研究需要讀取傳入消息的應用程序。現在,我發現我需要使用BroadcastReceiver類中的onReceive方法。現在我知道java不允許擴展兩個類,所以如何讓它工作,我一直堅持這個從很長一段時間,請幫助!如果還有其他方法可以做到這一點,請做引用。如何在另一個類的活動中設置偵聽器?
公共類SMS擴展活動按鈕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); }
類SMSBroadcastReceiver擴展廣播接收器{
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(); } } } } }
在收到消息後,您試圖達到什麼目的?提供更多信息 – Libin
@利賓其實我只需要訪問活動開始後收到的最後一條消息。 – achiever202
使你的'BroadcastReceiver'成爲你的'Activity'的一個內部類。 – Squonk