我想知道以编程方式注册广播接收器的最佳实践/方法是什么.我想根据用户的选择注册特定的接收器.
由于注册是通过清单文件完成的,我想知道是否有一种正确的方法可以在代码中实现这一点.
我想使用BroadcastReceiver具有引用的动态注册,Activity以便它可以修改其UI.我正在使用Context.registerReceiver()方法,但接收方的onReceive()方法永远不会被调用.
以下是显示问题的示例代码:
package com.example;
import android.app.Activity;
import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
public class RegisterBroadcastReceiver extends Activity {
public static class MyIntentService extends IntentService {
public MyIntentService() {
super(MyIntentService.class.getSimpleName());
}
@Override
protected void onHandleIntent(Intent intent) {
Intent i = new Intent(this, MyBroadcastReceiver.class);
sendBroadcast(i);
}
}
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(MyBroadcastReceiver.class.getSimpleName(),
"received broadcast"); …Run Code Online (Sandbox Code Playgroud) 我已经查看了一些SMS消息示例,而活动通常用于接收SMS.但是,我想要做的是让我的后台服务接收SMS(该服务将处理该消息并决定它是否适用于该应用程序 - 然后通知用户)
在我的清单中,服务定义如下:
<service android:name=".service.myService"
android:enabled="true">
<intent-filter>
<action android:name="package.com.service.myService"/>
</intent-filter>
</service>
Run Code Online (Sandbox Code Playgroud)
有服务收到短信,这会有用吗?
<receiver android:name=".service.myService" android:exported="true" >
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
我研究的示例代码来自:http://www.apriorit.com/our-company/dev-blog/227-handle-sms-on-android
我无法测试它,因为我的开发模块没有电话号码来发送短信.
几个小时以来我一直在努力.我还检查了文档和几个主题.我发现这个代码有两个主题,两个人都说代码工作正常,但不能在我的电脑上运行.第一个Toast出现了,但第二个Toast出现了.怎么了?
public class HelloAndroid2 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
}
public final class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}
Run Code Online (Sandbox Code Playgroud)
}