![](/img/trans.png)
[英]BroadcastReceiver within a Service not receiving broadcasts Android
[英]BroadcastReceiver inside activity not receiving broadcasts from service
我正在制作一個具有活動和intentservice的應用程序,該應用程序在后台執行一些加速度計的工作。 我嘗試發送廣播以將我的UI從服務更新為活動。 我在活動的onCreate()方法內創建了一個廣播接收器
public class MainActivity extends Activity {
BroadcastReceiver receiver;
public static String TAG = "vic.zerotosixty";
@Override
protected void onCreate(Bundle savedInstanceState) {
intentFilter = new IntentFilter();
intentFilter.addAction(SpeedService.ACTION_UPDATE_ACCELERATION);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"Broadcast Received");
Bundle bundle = intent.getExtras();
double acceleration = (double) bundle.get("acceleration");
speedText.setText((3.6*acceleration) + " Km/h"); //Update text field (3.6 is a unit conversion factor)
}
};
registerReceiver(receiver, intentFilter);
我的服務如下所示:
public class SpeedService extends IntentService implements SensorEventListener {
public final static int METHOD_INITIALIZE = 0;
public final static int METHOD_STOP = 1;
public final static String ACTION_UPDATE_ACCELERATION = "update_acceleration";
public final static String TAG = "vic.zerotosixty";
int initialized = 0;
double x,y,z,a;
//LocalBroadcastManager broadcast;
Intent sendAcceleration;
Sensor accel;
SensorManager sm;
onHandleIntent,似乎工作正常
protected void onHandleIntent(Intent intent) {
Bundle bundle = intent.getExtras();
int method = (int) bundle.get("method");
switch(method) {
case METHOD_INITIALIZE:
if (initialized == 0) {initialize();}
break;
default:
break;
}
}
private void initialize() {
Log.d(TAG, "initialized");
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accel = sm.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sm.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);
sendAcceleration = new Intent(this,MainActivity.class);
sendAcceleration.setAction(ACTION_UPDATE_ACCELERATION);
//broadcast = BroadcastManager.getInstance(this);
initialized = 1;
}
這是廣播的發送來源
public void onSensorChanged(SensorEvent event) {
x = event.values[0];
y = event.values[1];
z = event.values[2];
a = Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2));
sendAcceleration.putExtra("acceleration", a);
sendBroadcast(sendAcceleration);
Log.d(TAG,"broadcast sent");
}
從監視日志中可以看到發送的廣播 ,但從未收到 。 無法完成像從服務向活動中發送某些內容這樣簡單的事情,這使我望而卻步。 有任何想法嗎?
第一次進行此操作時,我遵循以下步驟:
https://developer.android.com/training/run-background-service/report-status.html
嘗試活動:
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, intentFilter);
在服務中:
LocalBroadcastManager.getInstance(this).sendBroadcast(sendAcceleration);
弄清楚了...
sendAcceleration = new Intent(this,MainActivity.class);
本來應該
sendAcceleration = new Intent();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.