【问题标题】:Toast not shown for simple SMS broadcast receiver简单 SMS 广播接收器未显示 Toast
【发布时间】:2016-01-31 14:52:47
【问题描述】:

我是一名Android初学者,我编写了以下代码,该代码可以在API 10的手机中显示toast,但我无法在API 19的手机中显示toast并运行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>

【问题讨论】:

    标签: android android-toast android-broadcastreceiver


    【解决方案1】:

    首先通过从 Android 默认 BroadcastReceiver 类扩展来创建您自己的 Receiver 类。然后 @Override 类中的 onReceive() 方法。这个onReceive() 方法将在新的短信到达手机时被调用。下面是我接收短信通知的接收器类。

    //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. 在项目的清单文件中注册广播接收器。如果您将使用此方法,那么您将无法控制广播接收器的生命周期。这意味着除非您卸载应用程序,否则您的应用程序将收到通知。

    2. 使用 Android 的 Context.registerReceiver() 方法注册广播接收器。通过使用这种方法,我们可以根据您的要求通过注册和注销广播接收器来控制它的生命周期。使用 Android 的 Context visit this Answer注册广播接收器

    因此,让我们在 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多