下面是一個服務,活動和廣播接收機的例子。活動是對服務進行更改的設置。廣播接收機收聽設置中的更改並更新服務。 learner2learner如何使用android廣播接收機
public class xService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public static void setEnableNotification(int command) {
Log.i("EnableNotification","Updated");
if (command == 0)
enableNotification = true;
...
}
}
下面的方法是發送一個活動的一部分廣播:
@Override
protected void onCreate(Bundle savedInstanceState) {
....
IntentFilter filter = new IntentFilter();
filter.addAction(NotifyServiceReceiver.ACTION);
registerReceiver(receiver,filter);
}
final String ACTION="broadcast_settings";
public void onClick(View view) {
Intent intent = new Intent(ACTION);
switch (view.getId()) {
case R.id.switchNotification:
if(switchNotification.isChecked()==true)
{
intent.putExtra("EnableNotification", 0);
Log.i("Security365","Notification is enabled.");
}
else if ....
sendBroadcast(intent);
break;
}
下面的部分是我的廣播接收機:
public class xReceiver extends BroadcastReceiver {
final String ACTION="broadcast_settings";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ACTION)){
int enableNotification = intent.getIntExtra("EnableNotification", 0);
if (enableNotification == 0)
Serurity365Service.setEnableNotification(0);
...
}
}
}
Mainfest
<receiver android:name=".xReceiver" android:enabled="true"></receiver>
在onReceive中添加了Log.i,它不工作。如果(enableNotification == 1) – Milan 2012-02-08 15:51:29
我還有另一種說法 – Milan 2012-02-08 15:53:43
您已經在if(intent.getAction()。equals(ACTION)){'right? – ccheneson 2012-02-08 16:31:10