Android:将传感器数据从服务广播到活动



我正在尝试学习Android应用程序开发,并编写了一个非常简单的应用程序,该应用程序由调用服务的活动组成。该服务向活动广播测量的加速度。问题是服务运行正常,但它不会将数据发送回活动。即,我的接收器上的onReceive从未被调用。此外,当活动结束时,会出现一个异常,表示我的接收者尚未注册。下面是我的服务代码activity和manifest.xml。如果有任何帮助,我们将不胜感激。

活动呼叫服务:

package com.practice;
import com.practice.SimpleService;
import android.app.Activity;
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.Window;
public class ServiceActivity extends Activity {
MyReceiver myReceiver=null;
Intent i;
static final String LOG_TAG = "ServiceActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.d( LOG_TAG, "onCreate" );
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.main);
    //Start service 
    i= new Intent(this, com.practice.SimpleService.class);
    Log.d( LOG_TAG, "onCreate/startService" );  
}
@Override 
public void onResume(){
    super.onResume();
    Log.d( LOG_TAG, "onResume/registering receiver" );  
    //Register BroadcastReceiver to receive accelerometer data from service
    //if (myReceiver == null){
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();      
        intentFilter.addAction(SimpleService.MY_ACTION);
        startService(i);  
        registerReceiver(myReceiver, intentFilter);
    //}     
}
@Override 
public void onPause(){
    super.onPause();
    Log.d( LOG_TAG, "onPause/unregistering receiver" ); 
    stopService(i);
    if (myReceiver != null)unregisterReceiver(myReceiver);      
}
@Override
protected void onStop(){
    super.onStop();
    Log.d( LOG_TAG, "onStop" );
    if (myReceiver != null) unregisterReceiver (myReceiver);
    stopService(i);
}
private class MyReceiver extends BroadcastReceiver{
    static final String Log_Tag = "MyReceiver";
    @Override
    public void onReceive(Context arg0, Intent arg1){
        Log.d( LOG_TAG, "onReceive" );
        String measurement = arg1.getStringExtra("measurement");        
        System.out.println("I am here");
    }
}   

}

服务获取传感器数据:

package com.practice;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;
public class SimpleService extends Service implements SensorEventListener{
 final static String MY_ACTION = "MY_ACTION";
   private TextView output;
   private String reading;
   private SensorManager mgr;
   private List<Sensor> sensorList;
   static final String LOG_TAG = "SimpleService";
   Intent intent = new Intent("com.practice.SimpleService.MY_ACTION");
   @Override
   //public void onStartCommand() {
   public void onCreate() {
      Log.d( LOG_TAG, "onStartCommand" );
      mgr = (SensorManager) getSystemService(SENSOR_SERVICE);
      sensorList = mgr.getSensorList(Sensor.TYPE_ACCELEROMETER);
      for (Sensor sensor : sensorList) {
         mgr.registerListener(this, sensor,
                 SensorManager.SENSOR_DELAY_NORMAL);
      }
   }
   @Override
   public void onDestroy() {
        Log.d( LOG_TAG, "onDestroy" );
        mgr.unregisterListener(this);       
        super.onDestroy();
   }
@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub      
}
@Override
public void onSensorChanged(SensorEvent event) {
      Log.d( LOG_TAG, "onSensorChanged" );
      StringBuilder builder = new StringBuilder();
      for (int i = 0; i < event.values.length; i++) {
         builder.append("   [");
         builder.append(i);
         builder.append("] = ");
         builder.append(event.values[i]);
         builder.append("n");
      }
      reading=builder.toString();
      //Send back reading to Activity
      intent.putExtra("measurement", reading);
      sendBroadcast(intent);        
}

}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.practice"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".SimpleService" ></service>
    </application>
</manifest>

创建自定义意图:

final static String MY_ACTION = "com.practice.SimpleService.MY_ACTION";

在Manifest.xml中

<receiver android:name=".MyReceiver" android:enabled="true">
  <intent-filter>
     <action android:name="com.practice.SimpleService.MY_ACTION"></action>
  </intent-filter>
</receiver>

有关自定义广播的更多信息,请参阅带有接收器的自定义意图和广播

最新更新