마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

현재 속도 표시하는 예제.. 코드를 다 쳤는데 로그가 뜨면서 실행이 안되네요

0 추천

소스코드는 다음과 같습니다.

public class SpeedometerActivity extends ActionBarActivity {
 
    SensorManager sensors;
    TextView tvSpeed;
     
    float velocity = 0f ; // 계산된 속도
    float currentAcceleration = 0f; //현재가속도
    float appliedAcceleration = 0f; // 적용된 가속도
    Date lastUpdated; //마지막 계산 시간
     
    Handler handler = null;
    Timer timer = null;
     
    private final SensorEventListener sensorEventListener =
            new SensorEventListener(){
        double calibrator = Double.NaN;
         
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy){
             
        }
         
        @SuppressWarnings("deprecation")
        @Override
        public void onSensorChanged(SensorEvent event){
             
        double x = event.values[SensorManager.DATA_X]; 
        double y = event.values[SensorManager.DATA_Y];
        double z = event.values[SensorManager.DATA_Z];
        double a = 
        (-1)* Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) +
                Math.pow(z, 2));
         
            if(calibrator == Double.NaN){
                calibrator =a;
            }
            else {
                computeVelocity();
                currentAcceleration = (float)a;
            }
            }
     
    };
     
 
    @SuppressLint("ServiceCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speedometer);
        //oncreate 이벤트 핸들러에서 registerListener() 메서드를 호출하여 센서가 발생시키는 이벤트를 감시할
                //SensorEventListener 인터페이스를 등록합니다. 그리고 속도를 표시할 textview컨트롤을 덕고 갱신시간을 초기화합니다.
                 
                tvSpeed = (TextView)findViewById(R.id.text_meter);
                lastUpdated = new Date(System.currentTimeMillis());
         
 
                sensors =
                        (SensorManager)getSystemService(Context.SEARCH_SERVICE);
                 
                sensors.registerListener(sensorEventListener,
                        sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                        SensorManager.SENSOR_DELAY_FASTEST);
                     
                //Timer를 통하여 매 1초에 한번씩 화면을 갱신하도록 학위해 이벤트 핸들러를 수정한다.
                    timer = new Timer("updateVelocity");
                     
                    timer.scheduleAtFixedRate(new TimerTask(){
                        public void run(){
                        updateScreen();
                }
                    }, 0, 1000);
                     
 
 
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.speedometer, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
 
    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
 
        public PlaceholderFragment() {
        }
 
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_speedometer,
                    container, false);
            return rootView;
        }
    }
 
    //속도변화를 계산하는 메서드. 
    private void computeVelocity(){
        Date now = new Date(System.currentTimeMillis());
        long timeGap = now.getTime() - lastUpdated.getTime();
        lastUpdated.setTime(now.getTime());
         
        float velocityGap = appliedAcceleration*(timeGap/1000);
     
        appliedAcceleration = currentAcceleration;
        velocity += velocityGap;
         
        double kmh =(Math.round(100*velocity*3.6)) / 100; //가속도 센서의 단위가 m/s이므로 일반적인 속도 단위이 km/h로 표시하기위해 3.6곱함
     
        tvSpeed.setText(String.valueOf(kmh) + "" +
        getString(R.string.speed_unit));
    }
     
    //Handler 객체를 통해 화면을 갱신하는 updateScreen()메서드 구현
        private void updateScreen(){
            final double kmh = (Math.round(100* velocity *3.6)) /100;
             
            handler.post(new Runnable(){
                public void run(){
                    tvSpeed.setText(String.valueOf(kmh) + " " + getString(R.string.speed_unit));
                }
            });
        }  
}

로그는 다음과 같습니다.

03-24 23:37:17.893: E/AndroidRuntime(26692): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.speedometer_3/com.example.speedometer_3.SpeedometerActivity}: java.lang.ClassCastException: android.app.SearchManager cannot be cast to android.hardware.SensorManager
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.app.ActivityThread.access$700(ActivityThread.java:159)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.os.Handler.dispatchMessage(Handler.java:99)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.os.Looper.loop(Looper.java:137)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.app.ActivityThread.main(ActivityThread.java:5419)
03-24 23:37:17.893: E/AndroidRuntime(26692): at java.lang.reflect.Method.invokeNative(Native Method)
03-24 23:37:17.893: E/AndroidRuntime(26692): at java.lang.reflect.Method.invoke(Method.java:525)
03-24 23:37:17.893: E/AndroidRuntime(26692): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
03-24 23:37:17.893: E/AndroidRuntime(26692): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
03-24 23:37:17.893: E/AndroidRuntime(26692): at dalvik.system.NativeStart.main(Native Method)
03-24 23:37:17.893: E/AndroidRuntime(26692): Caused by: java.lang.ClassCastException: android.app.SearchManager cannot be cast to android.hardware.SensorManager
03-24 23:37:17.893: E/AndroidRuntime(26692): at com.example.speedometer_3.SpeedometerActivity.onCreate(SpeedometerActivity.java:86)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.app.Activity.performCreate(Activity.java:5372)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
03-24 23:37:17.893: E/AndroidRuntime(26692): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
 
익명사용자 님이 2014년 3월 24일 질문

1개의 답변

0 추천

sensors = (SensorManager)getSystemService(Context.SEARCH_SERVICE);

 

위의 센서 매니저를 사용하시는데.. 뒤에 시스템 서비스가 틀렸네요.

아래와 같이 바꿔주세요~

 

(SensorManager)getSystemService(SENSOR_SERVICE);

초보개발자ㅠ (33,870 포인트) 님이 2014년 3월 25일 답변
감사합니다..그런데도 에러가 계속나네요.. 폰에서 실행시키면
앱이 중지되었다고 하면서 꺼져버립니다.. 이럴땐 어떡해야하죠?

로그는 다음과 같습니다.
03-25 19:57:18.512: E/AndroidRuntime(17027): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.speedometer_3/com.example.speedometer_3.SpeedometerActivity}: java.lang.ClassCastException: android.app.SearchManager cannot be cast to android.hardware.SensorManager

03-25 19:57:18.512: E/AndroidRuntime(17027): Caused by: java.lang.ClassCastException: android.app.SearchManager cannot be cast to android.hardware.SensorManager
흠.. 소스는 저게 다에요?
SearchManager 를 SensorManager 로 캐스팅할수 없다는건데
더이상 해당하는 부분이 안보이네요 '-'
...