安卓:广播传感器从业务数据到活动传感器、业务、数据

2023-09-09 21:03:41 作者:执著到心碎

我想学习Android应用开发和写了一个非常简单的应用程序包括一个调用服务的活动。该服务广播测量加速度活动。问题是,在服务运行确定,但它不发送数据返回到活性。即,对的onReceive我接收器不会被调用。此外,当活动结束时,有一个例外说我的接收机尚未注册。下面是我的code的服务,活动和manifest.xml中。任何帮助将非常AP preciated。

活动电话服务:

 包com.practice;进口com.practice.SimpleService;进口android.app.Activity;进口android.content.BroadcastReceiver;进口android.content.Context;进口android.content.Intent;进口android.content.IntentFilter;进口android.os.Bundle;进口android.util.Log;进口android.view.Window;公共类ServiceActivity延伸活动{MyReceiver myReceiver = NULL;我的意图;静态最后弦乐LOG_TAG =ServiceActivity;/ **当第一次创建活动调用。 * /@覆盖公共无效的onCreate(捆绑savedInstanceState){    Log.d(LOG_TAG的onCreate);    super.onCreate(savedInstanceState);    requestWindowFeature(Window.FEATURE_NO_TITLE);    的setContentView(R.layout.main);    //开始服务    I =新意图(这一点,com.practice.SimpleService.class);    Log.d(LOG_TAG的onCreate / startService);}@覆盖公共无效onResume(){    super.onResume();    Log.d(LOG_TAG,onResume /注册接收器);    //注册广播接收器接收来自服务加速度计数据    //如果(myReceiver == NULL){        myReceiver =新MyReceiver();        IntentFilter的IntentFilter的=新的IntentFilter();        intentFilter.addAction(SimpleService.MY_ACTION);        startService(ⅰ);        registerReceiver(myReceiver,IntentFilter的);    //}}@覆盖公共无效的onPause(){    super.onPause();    Log.d(LOG_TAG的onPause /注销接收);    stopService(ⅰ);    如果(myReceiver!= NULL)u​​nregisterReceiver(myReceiver);}@覆盖保护无效的onStop(){    super.onStop();    Log.d(LOG_TAG的onStop);    如果(myReceiver!= NULL)u​​nregisterReceiver(myReceiver);    stopService(ⅰ);}私有类MyReceiver扩展广播接收器{    静态最后弦乐Log_Tag =MyReceiver;    @覆盖    公共无效的onReceive(上下文为arg0,ARG1意向){        Log.d(LOG_TAG的onReceive);        串测量= arg1.getStringExtra(计量);        的System.out.println(我在这里);    }} 

}

服务获取传感器数据:

 包com.practice;进口的java.util.List;进口android.app.Service;进口android.content.Intent;进口android.hardware.Sensor;进口android.hardware.SensorEvent;进口android.hardware.SensorEventListener;进口android.hardware.SensorManager;进口android.os.IBinder;进口android.util.Log;进口android.widget.TextView;公共类SimpleService扩展服务实现SensorEventListener { 最终静态字符串MY_ACTION =MY_ACTION;   私人TextView的输出;   私人字符串阅读;   私人的SensorManager经理;   私人列表<传感器及GT; sensorList;   静态最后弦乐LOG_TAG =SimpleService;   意向意图=新意图(com.practice.SimpleService.MY_ACTION);   @覆盖   //公共无效onStartCommand(){   公共无效的onCreate(){      Log.d(LOG_TAGonStartCommand);      经理=(的SensorManager)getSystemService(SENSOR_SERVICE);      sensorList = mgr.getSensorList(Sensor.TYPE_ACCELEROMETER);      对于(传感器传感器:sensorList){         mgr.registerListener(这一点,传感器,                 SensorManager.SENSOR_DELAY_NORMAL);      }   }   @覆盖   公共无效的onDestroy(){        Log.d(LOG_TAG的onDestroy);        mgr.unregisterListener(本);        super.onDestroy();   }@覆盖公众的IBinder onBind(意向为arg0){    // TODO自动生成方法存根    返回null;}@覆盖公共无效onAccuracyChanged(传感器传感器,精度INT){    // TODO自动生成方法存根}@覆盖公共无效onSensorChanged(SensorEvent事件){      Log.d(LOG_TAGonSensorChanged);      StringBuilder的建设者=新的StringBuilder();      的for(int i = 0; I< event.values​​.length;我++){         builder.append([);         builder.append(ⅰ);         builder.append(] =);         builder.append(event.values​​ [I]);         builder.append(\\ n);      }      读= builder.toString();      //发送回读到活动      intent.putExtra(测量,读);      sendBroadcast(意向);} 

}

的Manifest.xml

 <?XML版本=1.0编码=UTF-8&GT?;<清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android    包=com.practice    安卓版code =1    机器人:=的versionName1.0>    <采用-SDK安卓的minSdkVersion =8/>    <应用        机器人:图标=@绘制/ ic_launcher        机器人:标签=@字符串/ APP_NAME>        <活动            机器人:ServiceActivityNAME =            机器人:标签=@字符串/ APP_NAME>            &所述;意图滤光器>                <作用机器人:名字=android.intent.action.MAIN/>                <类机器人:名字=android.intent.category.LAUNCHER/>            &所述; /意图滤光器>        < /活性GT;        <服务机器人:名字=SimpleService>< /服务>    < /用途>< /清单> 
数据治理平台技术解决方案 图文

解决方案

创建自定义的意图:

 最终静态字符串MY_ACTION =com.practice.SimpleService.MY_ACTION; 

在的Manifest.xml

 <接收机器人:名字=机器人MyReceiver:启用=真正的>  &所述;意图滤光器>     <作用机器人:名字=com.practice.SimpleService.MY_ACTION>< /作用>  &所述; /意图滤光器>< /接收器> 

为自定义发送的更多信息,请参阅自定义的意图和广播与接收器

I am trying to learn Android app development and wrote a very simple app consisting of an activity that calls a service. The service broadcasts measured acceleration to the activity. The problem is that the service runs ok but it does not send data back to the activity. i.e, onReceive on my receiver is never called. Also, when the activity ends, there is an exception saying that my receiver has not been registered. Below is my code for the service, activity and manifest.xml. Any help would be very much appreciated.

Activity calling service:

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");
    }

}   

}

Service getting sensor data:

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>

解决方案

Create a Custom Intent :

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

In Manifest.xml

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

for more information for Custom Broadcast see Custom Intents and Broadcasting with Receivers