2009-09-23 153 views

回答

18

您还必须修改Manifest文件。

这里是工作的例子:

这些变量和方法是服务类的成员:

public static final String MOVEMENT_UPDATE = "com.client.gaitlink.AccelerationService.action.MOVEMENT_UPDATE"; 
    public static final String ACCELERATION_X = "com.client.gaitlink.AccelerationService.ACCELERATION_X"; 
    public static final String ACCELERATION_Y = "com.client.gaitlink.AccelerationService.ACCELERATION_Y"; 
    public static final String ACCELERATION_Z = "com.client.gaitlink.AccelerationService.ACCELERATION_Z"; 

private void announceAccelerationChanges()//this method sends broadcast messages 
    { 
     Intent intent = new Intent(MOVEMENT_UPDATE); 
     intent.putExtra(ACCELERATION_X, accelerationX); 
     intent.putExtra(ACCELERATION_Y, accelerationY); 
     intent.putExtra(ACCELERATION_Z, accelerationZ); 

     sendBroadcast(intent); 
    } 

这是从主要业务的方法:

您必须先注册接收器在onResume方法中:

@Override 
    public void onResume() 
    { 

     IntentFilter movementFilter; 
     movementFilter = new IntentFilter(AccelerationService.MOVEMENT_UPDATE); 
     accelerationReceiver = new AccelerationServiceReceiver(); 
     registerReceiver(accelerationReceiver, movementFilter); 


     startAccelerationService(); 

     super.onResume(); 
    } 

    private void startAccelerationService() 
    { 
     startService(new Intent(this, AccelerationService.class)); 
    } 

    public class AccelerationServiceReceiver extends BroadcastReceiver 
    { 
     @Override 
     public void onReceive(Context context, Intent intent)//this method receives broadcast messages. Be sure to modify AndroidManifest.xml file in order to enable message receiving 
     { 
      accelerationX = intent.getDoubleExtra(AccelerationService.ACCELERATION_X, 0); 
      accelerationY = intent.getDoubleExtra(AccelerationService.ACCELERATION_Y, 0); 
      accelerationZ = intent.getDoubleExtra(AccelerationService.ACCELERATION_Z, 0); 

      announceSession(); 

      updateGUI(); 
     } 
    } 

这是t他是AndroidManifest.xml文件的一部分,必须设置该文件才能接收广播消息:

<activity android:name=".GaitLink" 
        android:label="@string/app_name"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 

       <action android:name="com.client.gaitlink.CommunicationService.action.ACTIVITY_STATUS_UPDATE" /> 

      </intent-filter> 
     </activity> 
+0

我已经尝试过这个,但它不能按预期工作。 我已经写了Log语句,但是没有在onRecieve方法中显示。有什么不对的地方,我可能会这样做,我正在做同样的说! – Sam97305421562 2009-09-24 09:42:09

+0

服务是否广播该消息? BroadcastReceiver是否已启动并正在运行? 您是否在AndroidManifest.xml中添加了意图过滤器? – 2009-09-24 10:39:19

+0

我已经在AndroidManifest.xml文件中添加了BroadcastReceiver,是的,服务进行广播,我如何确认BroadcastReceiver已经启动。 – Sam97305421562 2009-09-24 11:41:17

相关问题