后台服务,用于控制接近传感器 [英] Background service to control proximity sensor

查看:148
本文介绍了后台服务,用于控制接近传感器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要运行一个控制接近传感器状态的服务(总是在后台,即使关闭了应用程序,我也希望该服务不断进行检查),并在覆盖时启动活动.我尝试过,但是有错误.像这样的例子吗?

I need to run a service (always in background, I want the service constantly checking even if the application is closed) that control the proximity sensor status, and when it's covered launch an activity. I tried but I had error. Any examples of something like this?

P.S.在我的AndroidManifest中,我添加了:

P.S. In my AndroidManifest I added:

            <service
            android:name="xxx.xxxxx.xxxxx.MyService"
            android:enabled="true" />

这是我的MyService.java:(Eclipse不会报告任何错误,但是当我在设备上尝试执行此操作时,应用会强制关闭.)

Here my MyService.java: (Eclipse don't report any error but when I try it on my device, apps give a force close.)

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.widget.Toast;


public class MyService extends Service implements SensorEventListener {
Sensor proxSensor;
SensorManager sm;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
    sm=(SensorManager)getSystemService(SENSOR_SERVICE);
    proxSensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);

    sm.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    Intent panel = new Intent(this, Panel.class);
    startActivity(panel);
}
@Override
public void onDestroy() {
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}

    }

这里是我的Main.java:

And here my Main.java :

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.lino99.smartTask.R;

public class Main extends Activity implements OnClickListener {
Button buttonStart, buttonStop;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);

buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}

public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
  startService(new Intent(this, MyService.class));
  break;
case R.id.buttonStop:
  stopService(new Intent(this, MyService.class));
  break;
}
}
}

推荐答案

好的,您在代码中进行了一些更改,这些更改应清除您的错误并使服务继续进行,并且接近传感器具有响应能力:

ok here are few changes in your code that should clear your errors and make your service ongoing and your proximity sensor responsive:

这是您的服务的外观:

@Override
public void onCreate() {//onCreat shouldn't be used for sensor u should use onStartCommand
    Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    //here u should use the following code otherwise your sensor will be crazy
    if(event.values[0] == 0){
    Intent panel = new Intent(this, Panel.class);
    startActivity(panel);
    }
}
@Override
public void onDestroy() {//here u should unregister sensor
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
    sm.unregisterListener(this);
}

@Override//here u should register sensor and write onStartCommand not onStart
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    sm=(SensorManager)getSystemService(SENSOR_SERVICE);
    proxSensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    sm.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);

    //here u should make your service foreground so it will keep working even if app closed

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent bIntent = new Intent(MyService.this, MainActivity.class);       
    PendingIntent pbIntent = PendingIntent.getActivity(MyService.this, 0 , bIntent, 0);
    NotificationCompat.Builder bBuilder =
            new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Title")
                .setContentText("Subtitle")
                .setAutoCancel(true)
                .setOngoing(true)
                .setContentIntent(pbIntent);
    barNotif = bBuilder.build();
    this.startForeground(1, barNotif);

        //then you should return sticky
        return Service.START_STICKY;
}

}

好吧,现在尝试代码,让我知道它如何为您工作,希望能对您有所帮助.

Ok now try the code and let me know how it works for you, hope I helped.

这篇关于后台服务,用于控制接近传感器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆