Объединение 2 расширенных действий для SMS-уведомлений: D - PullRequest
0 голосов
/ 25 февраля 2012

Итак, я хочу создать приложение, которое будет уведомлять пользователя каждый раз, когда приходит SMS.Моя главная проблема - я запутался, как объединить мои 2 занятия / занятия.Я расширяю BroadcastReceiver в классе SMSReceiver, чтобы он мог определять, приходят ли какие-либо новые SMS, и я расширяю Activity в своем классе SMSNotif.Проблема в том, что я НЕ МОГУ РАСШИРЯТЬ БОЛЬШЕ 1 КЛАССА в каждом действии.

Это класс SMSReceiver:

public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent arg1) {
    // TODO Auto-generated method stub

    Bundle bundle = arg1.getExtras();
    SmsMessage[] msgs = null;
    String str = "";
    if (bundle != null) {
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];

        for (int i = 0; i < msgs.length; i++) {
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            str += "SMS from " + msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            str += "\n";
        }

        Toast.makeText(arg0, str, Toast.LENGTH_SHORT).show();
    }
    //Intent i = new Intent(SMSReceiver.this, SMSNotif.class);
}

}

И это мой класс SMSNotif:

public class SMSNotif extends Activity{
static final int HELLO_ID = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    //String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    //int icon = R.drawable.ic_launcher;
    String tickerText = "Hello";
    //long when = System.currentTimeMillis();

    Notification notification = new Notification(R.drawable.ic_launcher, tickerText, System.currentTimeMillis());

    //Context context = getApplicationContext();
    String contentTitle = "My notification";
    String contentText = "Hello World!";
    Intent notificationIntent = new Intent(this, SMSNotif.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
    notification.defaults = Notification.DEFAULT_ALL;
    mNotificationManager.notify(HELLO_ID, notification);

}

}

Опять же, мой главный вопрос: как объединить эти действия, чтобы каждый раз, когда пользователь получал новое SMS, мое приложение показывало его уведомление (а не только форму тоста)SMSNotif).

1 Ответ

0 голосов
/ 26 февраля 2012

Вот способ решения вашей проблемы:

Сделайте класс BroadcastReceiver локальным для класса Activity.Таким образом, получатель может что-то сделать в упражнении

public class SMSNotif extends Activity{

    class SMSReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            ...
            someActivityMetod("Hello world from receiver");
        }

    }

    void someActivityMetod(String message)
    {
        ...
    }
}

, вы также должны (не) зарегистрировать получателя в коде действий

public class SMSNotif extends Activity{

            BroadcastReceiver myReceiver = null;



    @Override
    public void onPause()
    {

        if (myReceiver != null)
        {
            unregisterReceiver(myReceiver);
            myReceiver = null;
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (myReceiver == null)
        {
            myReceiver = new SMSReceiver();
            IntentFilter filter = new IntentFilter("Some.Action.Code");
            registerReceiver(myReceiver, filter);
        }
    }
...