Problem with alert in smsRecevicer class
I am new here. I are making a app, where it must show a alert on sms message. I don't think I understand how i ex. can call a function from another class, when the function have a "this"-attribute.
But this line do not work:
AlertDialog.Builder(this).setTitle("asd").setMessa ge(str).setNegativeButton("Annuller", null).setPositiveButton("Bekræft", null).show();
I am not sure if it is because of this class run i background or what?
This is the class:
package net.sms;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
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";
}
AlertDialog.Builder alt_bld = new AlertDialog.Builder(context);
alt_bld.setTitle("aaa");
alt_bld.show();
//new AlertDialog.Builder(this).setTitle("asd").setMessage(str).setNegativeButton("Annuller", null).setPositiveButton("Bekræft", 开发者_如何学运维null).show();
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}
I don't think you could start an alert in a Broadcast Receiver. You could achieve a similar affect by starting an activity that looks like an alert. Note: Google does not recommend starting activities from background services or receivers.
Manifest.xml
<activity android:name="AlertActivity" android:theme="@android:style/Theme.Dialog" />
alert_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="fill_parent">
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content">
<Button android:id="@+id/positiveButton" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Annuller" />
<Button android:id="@+id/negativeButton" android:layout_weight="1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Bekraft" />
</LinearLayout>
</LinearLayout>
SmsReceiver.java
context.startActivity(new Intent(context, AlertActivity.class));
Receivers don't like alert dialogs. You can use a notification or toast.
精彩评论