Использование 2-х вложенных классов для получения уведомлений от новых SMS - PullRequest
0 голосов
/ 27 февраля 2012

Я уже задавал вопрос здесь: объединение-2-расширенная-активность-для-смс-уведомления

И теперь я получаю новую проблему: D

Поэтому я уже создаю вложенный класс следующим образом:

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

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);
    }
}

@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);

}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    if(myReceiver != null){
        unregisterReceiver(myReceiver);
        myReceiver = null;
    }
    super.onPause();
}

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

    if(myReceiver == null){
        myReceiver = new SMSReceiver();
        IntentFilter filter = new IntentFilter();
        registerReceiver(myReceiver, filter);
    }
}

}

И мой МАНИФЕСТ выглядит так:

 <activity
        android:name=".SMSNotif"
        android:label="@string/app_name" >
         <receiver android:name=".SMSReceiver" >
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
    </activity>

Проблема в том, мойприложение не может обнаружить новые SMS сейчас ... Где моя ошибка? это в моем манифесте?Я уже пытался изменить свои коды, но я все еще не могу решить свою проблему ... Итак, вопрос: Можете ли вы помочь мне, чтобы мое приложение могло обнаруживать новые SMS и отправлять уведомления каждый раз, когда приходит новое SMS? Спасиботебе очень понравилось!: D И извините, если я допустил некоторые ошибки, английский не является моим родным языком :) У меня есть идея: я попытался изменить класс, поэтому SMSReceiver будет внешним, а SMSNotif будет внутри него ...возможно ли это? (я пробовал это, и у меня есть некоторые ошибки). Я думаю, что с помощью обратного, BroadcastReceiver сможет обнаруживать новые SMS ... это правда?

Ответы [ 2 ]

1 голос
/ 27 февраля 2012

Вы должны указать, что ваш получатель находится во внутреннем классе в манифесте.

     <activity
            android:name=".SMSNotif"
            android:label="@string/app_name" >

        </activity>

 <receiver android:name="your.package.name.SMSNotif$SMSReceiver" >
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

Приемник не должен быть активным.

и ваш внутренний класс SMSReceiver должен быть статическим

РЕДАКТИРОВАНИЕ Если вы хотите просто показать уведомление, тогда действие не требуется.

public class SMSReceiver extends BroadcastReceiver {

    private static final int HELLO_ID = 0;

    @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();

            // String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager mNotificationManager = (NotificationManager) arg0
                    .getSystemService(Context.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(arg0, SMSNotif.class);
            PendingIntent contentIntent = PendingIntent.getActivity(arg0, 0,
                    notificationIntent, 0);

            notification.setLatestEventInfo(arg0, contentTitle, contentText,
                    contentIntent);
            notification.defaults = Notification.DEFAULT_ALL;
            mNotificationManager.notify(HELLO_ID, notification);
        }
    }
}
1 голос
/ 27 февраля 2012

Я не уверен, что это решит вашу проблему или нет, но я думаю, вам следует попробовать внести следующие изменения в файл манифеста:

<activity
        android:name=".SMSNotif"
        android:label="@string/app_name" >        
</activity>
<receiver android:name="com.your.path.SMSNotif$SMSReceiver" >
        <intent-filter android:priority="100" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
</receiver>

Надеюсь, это решит вашу проблему. Поскольку получатель широковещания является внутренним классом класса SMSNotif, вам придется указать полный путь вместе с ActivityName $ RecevierName, как показано выше.

РЕДАКТИРОВАТЬ:

Я добавил тег intent-filter (см. Код выше). Это уведомит ваше приложение, прежде чем оно будет уведомлять Android OS о новых смс.

...