我如何在后台 运行 这个 Android 代码

How can I run this Android code in Background

这实际上是一个拼贴项目。要求是:

  1. 制作一个应用程序,使用任意两个传感器(我使用接近传感器和加速计)将 Android 配置文件更改为铃声、振动和静音。
  2. 即使在应用程序关闭后,也要确保该应用程序 运行 仍在后台。
  3. 持续运行宁传感器消耗太多电池,做一些事情是为了尽可能节省电池电量。

我已经完成了第 1 项并按预期运行,只剩下 2 和 3。 在后台 运行 这段代码的最简单方法是什么:我有这样的想法:

我想使用两个按钮启动和停止后台服务。

这是 NO 的代码:1。

public class SensorActivity extends Activity implements SensorEventListener{

private SensorManager mSensorManager;
private Sensor proxSensor,accSensor;

private TextView serviceStatus,profileStatus;
private Button startService,endService;

private boolean isObjectInFront,isPhoneFacedDown;

private AudioManager audioManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sensor);

    audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    proxSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    accSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    isObjectInFront = false;
    isPhoneFacedDown = false;

    serviceStatus = (TextView) findViewById(R.id.textView_serviceStatus);
    profileStatus = (TextView) findViewById(R.id.textView_profileStatus);
}

protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
    mSensorManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_NORMAL);
}


protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
}

@Override
public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
        if(event.values[0] > 0){
            isObjectInFront = false;
        }
        else {
            isObjectInFront = true;
        }

    }
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        if(event.values[2] < 0){
            isPhoneFacedDown = true;
        }
        else {
            isPhoneFacedDown = false;
        }
    }

    if(isObjectInFront && isPhoneFacedDown){
        audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        profileStatus.setText("Ringer Mode : Off\nVibration Mode: Off\nSilent Mode: On");
    }
    else {
        if(isObjectInFront){
            audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            profileStatus.setText("Ringer Mode : Off\nVibration Mode: On\nSilent Mode: Off");
        }
        else {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            profileStatus.setText("Ringer Mode : On\nVibration Mode: Off\nSilent Mode: Off");
        }
    }



}

@Override
public void onAccuracyChanged(Sensor sensor, int i) {

}

}

您绝对应该使用 服务

Android 用户界面被限制为执行长时间的 运行ning 作业,以使用户体验更流畅。一个典型的长 运行ning 任务可以是定期从 Internet 下载数据、将多条记录保存到数据库、执行文件 I/O、获取您的 phone 联系人列表等。对于如此长的 运行宁任务,服务是替代。

服务是用于在后台执行长时间 运行ning 任务的应用程序组件。 服务没有任何用户界面,也不能直接与 activity 通信。 服务可以 运行 无限期地在后台运行,即使启动该服务的组件已被销毁。 通常,服务总是执行单个操作并在预期任务完成后自行停止。 应用实例主线程中的一个服务运行s。它不会创建自己的线程。如果您的服务要执行任何长时间 运行ning 阻塞操作,它可能会导致应用程序无响应 (ANR)。因此,您应该在服务中创建一个新线程。

例子

服务class

public class HelloService extends Service {

    private static final String TAG = "HelloService";

    private boolean isRunning  = false;

    @Override
    public void onCreate() {
        Log.i(TAG, "Service onCreate");

        isRunning = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i(TAG, "Service onStartCommand");

        //Creating new thread for my service
        //Always write your long running tasks in a separate thread, to avoid ANR
        new Thread(new Runnable() {
            @Override
            public void run() {


                //Your logic that service will perform will be placed here
                //In this example we are just looping and waits for 1000 milliseconds in each loop.
                for (int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }

                    if(isRunning){
                        Log.i(TAG, "Service running");
                    }
                }

                //Stop service once it finishes its task
                stopSelf();
            }
        }).start();

        return Service.START_STICKY;
    }


    @Override
    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "Service onBind");
        return null;
    }

    @Override
    public void onDestroy() {

        isRunning = false;

        Log.i(TAG, "Service onDestroy");
    }
}

清单声明

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javatechig.serviceexample" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
    <activity
        android:name=".HelloActivity"
        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 declared in manifest -->
    <service android:name=".HelloService"
        android:exported="false"/>
</application>

开始您的服务

Intent intent = new Intent(this, HelloService.class);
startService(intent);

Reference