Toast未显示简单的SMS广播接收器

时间:2015-10-31 05:55:04

标签: android android-toast android-broadcastreceiver

我是一名Android初学者,我编写了以下代码,代码可以显示带有API 10的手机中的吐司,但我无法显示吐司并使用API​​ 19在手机中运行onReceive。

我搜索了互联网,发现我应该使用 flag_include_stopped_pa​​ckages 在意图上添加标记。我想这就是我的问题的答案。

但是如何将其添加到系统广播?感谢是否有人可以显示合适的代码。我找不到任何合适的代码来自互联网显示这一点。谢谢!

SMS.java

public class SMS extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

IncomingSms.java

public class IncomingSms extends BroadcastReceiver {
    final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context,Intent intent) {
    final Bundle bundle = intent.getExtras();
    try {
        if (bundle != null) {
            final Object[] pdusObj = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdusObj.length; i++) {
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String message = currentMessage.getDisplayMessageBody();
                String senderNum = currentMessage.getDisplayOriginatingAddress();
                Log.i("SmsReceiver", senderNum + message);
                Toast.makeText(context,
                        "send from " + senderNum + message, Toast.LENGTH_LONG).show();

            }
        }
    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" + e);
    }
}
}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.security.security" >

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".SMS"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.INFO"/>
        </intent-filter>
    </activity>

    <receiver android:name=".IncomingSms">
        <intent-filter android:priority="999">
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
    </receiver>

</application>

1 个答案:

答案 0 :(得分:0)

首先通过从Android默认BroadcastReceiver类扩展来创建自己的Receiver类。然后@Override您班级中的onReceive()方法。当新短信进入手机时,将调用此onReceive()方法。以下是我的Receiver Class,用于收到短信通知。

//Here is your broadcast receiver class
public class YourBroadcastReceiver extends BroadcastReceiver{
    private static final String TAG = "MyBroadCastReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
    Log.i(TAG,"OnReceive ++>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            Bundle bndl = intent.getExtras();
            SmsMessage[] msg = null;
            String str = "";         
            if (null != bndl)
            {
                //---retrieve the SMS message received---
                Object[] pdus = (Object[]) bndl.get("pdus");
                msg = new SmsMessage[pdus.length];         
                for (int i=0; i<msg.length; i++){
                    msg[i] = SmsMessage.createFromPdu((byte[])pdus[i]);             
                    str += "SMS From " + msg[i].getOriginatingAddress();                   
                    str += " :\r\n";
                    str += msg[i].getMessageBody().toString();
                    str += "\n";
                }
                //---display incoming SMS as a Android Toast---
                Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
            } 
        }
}

在Android中注册广播接收器有两种不同的方法。

  1. 在项目的清单文件中注册broadcastreceiver。如果您将使用此方法,则无法控制广播接收器的生命周期。这意味着除非您卸载应用程序,否则您的应用程序将收到通知。

  2. 使用Android的Context.registerReceiver()方法注册broadcastreceiver。通过使用此方法,我们可以根据您的要求通过注册和取消注册广播接收器来控制其生命周期。使用Android的上下文visit this Answer

  3. 注册广播接收者

    因此,让我们使用Manifest文件中的传入SMS意图过滤器注册您自己的Receiver类。对于传入的SMS示例,我的清单文件如下所示。

    <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="19" />
    
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    
    <receiver
            android:name ="FULL_PACKAGE_NAME.YourBroadcastReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
       </receiver>
    

    就是这样。安装应用程序后,当时广播接收器将自动注册Android操作系统,您将收到有关详细信息的Android Toast通知。

    获取更多信息visit here