我想構建一個簡單的應用程序,將等待一個新的SMS到達,提取並處理來自它的數據。應用程序應該在後臺運行。 GUI有一個開關元件來啓動/停止廣播接收器。即使應用程序被破壞並且屏幕被鎖定,應用程序仍應該工作,除非用戶手動將其關閉。 我搜索了每一個在stackoverflow上的資源,其中大多數都是這樣做的,但它仍然不適用於我,我似乎無法知道爲什麼。我知道,因爲Log.d(...)
沒有返回任何東西。任何幫助,將不勝感激。廣播接收器不被稱爲
廣播SMS接收
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("RECEIVER", "ENTERED");
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Log.d("RECEIVER", "SMS RECEIVED");
SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for(int i = 0; i < 4; i++){
SmsMessage sms = messages[i];
Log.d("Message " + i + 1 + " from: ", sms.getOriginatingAddress());
Toast.makeText(context,"SMS from " + sms.getOriginatingAddress(), Toast.LENGTH_SHORT).show();
}
}
}
}
主要活動
public class MainActivity extends AppCompatActivity {
IntentFilter filter;
SMSReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
receiver = new SMSReceiver();
Switch startSwitch = (Switch) findViewById(R.id.startSwitch);
startSwitch.setChecked(false);
startSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
getApplication().registerReceiver(new SMSReceiver(), filter);
} else {
getApplication().unregisterReceiver(receiver);
}
}
});
}
}
清單
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ahmad.smsforwarder">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
</manifest>
哪裏是你的清單上的接收器? –