簡體   English   中英

如何在后台運行此 Android 代碼

[英]How can I run this Android code in Background

這實際上是一個拼貼項目。 要求是:

  1. 制作一個應用程序,使用任意兩個傳感器(我使用接近度和加速度計)將 Android Profile 更改為 Ringer、Vibration 和 Silent。
  2. 確保應用程序即使在應用程序關閉后也在后台運行。
  3. 連續運行的傳感器消耗太多電池,做一些事情可以盡可能節省電池電量。

我已經完成了 NO: 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) {

}

}

您絕對應該使用Service

Android 用戶界面僅限於執行長時間運行的作業,以使用戶體驗更流暢。 一個典型的長時間運行的任務可以是定期從 Internet 下載數據、將多條記錄保存到數據庫、執行文件 I/O、獲取您的手機聯系人列表等。對於此類長時間運行的任務,服務是替代方案。

服務是用於在后台執行長時間運行任務的應用程序組件。 服務沒有任何用戶界面,也不能直接與活動通信。 服務可以無限期地在后台運行,即使啟動該服務的組件被銷毀。 通常,服務始終執行單個操作,並在預期任務完成后自行停止。 服務在應用程序實例的主線程中運行。 它不創建自己的線程。 如果您的服務要執行任何長時間運行的阻塞操作,則可能會導致應用程序無響應 (ANR)。 因此,您應該在服務中創建一個新線程。

例子

服務類

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

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM