我已經編寫了一個簡單的活動來測試服務和broacast接收器以及與之相關的服務。爲了知道它是否工作,我在主Activity中設置了一個Toast,一旦調用了OnReceive()方法就會顯示出來。但對於我的生活,我無法得到這個工作。Android:廣播接收器和服務問題
這些是代碼:
公共類ServicesAndBroadcastIntentActivity延伸活動{
private Toast test;
private Intent intent;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this,serviceD.class);
test = Toast.makeText(this,"Test",Toast.LENGTH_LONG);
test.setGravity(Gravity.CENTER,0,0);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
test.setText((intent.getStringExtra("EXTRA_MSG")));
test.show();
}
};
@Override
public void onResume(){
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(serviceD.BROADCAST_ACTION));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
}
公共類服務擴展服務{
private Intent intent;
static final String BROADCAST_ACTION = "com.mejg.ServicesAndBroadcastIntent";
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
public void onStart(){
intent.putExtra("EXTRA_MSG","hola");
sendBroadcast(intent);
stopSelf();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
我做了你的建議,從一個按鈕啓動服務並在開始服務之前註冊接收器,但它似乎仍然沒有工作。任何其他建議? – 2012-04-28 22:30:18
@rodkarom:不是我的頭頂。 FWIW,這裏有一個'LocalBroadcastManager'的示例用法,其設置與您的設置幾乎相同(儘管我使用'TextView'而不是'Toast')。你可能會暫時拋棄'setGravity()'來簡化'Toast',以防萬一搞砸 - 我很少改變我的'Toast'重力。 – CommonsWare 2012-04-28 22:40:30
還有一個疑問......我需要在AndroidManifest.xml中聲明一個intent-filter嗎? – 2012-04-28 22:49:11