我创建了一个broadcastReceiver
清单中的
<receiver android:name="SMSMonitor">
<intent-filter android:priority="100">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
类:
public class SMSMonitor extends BroadcastReceiver {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] messages = new SmsMessage[pduArray.length];
for (int i = 0; i < pduArray.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);
}
StringBuilder bodyText = new StringBuilder();
for (SmsMessage message : messages) {
bodyText.append(message.getMessageBody());
}
String body = bodyText.toString();
Observer.getInstance().send(new SmsEvent(body));
abortBroadcast();
}
}
启动时,我的应用程序接收器开始转动。但我在活动中有两个按钮&#34;开始&#34;并且&#34;停止&#34;。当我按下&#34;开始&#34;我想要启动接收器按下并停止按下&#34;停止&#34;按钮。我该怎么做?
答案 0 :(得分:3)
在onClick()
开始
public void enableBroadcastReceiver()
{
ComponentName receiver = new ComponentName(this, SMSMonitor.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, 'Enabled broadcast receiver', Toast.LENGTH_SHORT).show();
}
在onClick()
停止
// This method disables the Broadcast receiver registered in the AndroidManifest file.
* @param view
*/
public void disableBroadcastReceiver(){
ComponentName receiver = new ComponentName(this, SMSMonitor class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, 'Disabled broadcst receiver', Toast.LENGTH_SHORT).show();
}
答案 1 :(得分:0)
试试这个,
<receiver android:name="your receiver name">
主要活动
BroadcastReceiver broadcast = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
Log.w("Check", "Inside On Receiver");
Toast.makeText(getApplicationContext(), "onReceive", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BROADCAST_ACTION);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(broadcast, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcast);
}
}