2016-12-27 2 views
1

이것은 실제로 콜라주 프로젝트입니다. 요구 사항은 다음과 같습니다.백그라운드에서이 Android 코드를 실행하려면 어떻게해야합니까?

  1. 두 개의 센서 (근접 및 가속도계 사용)를 사용하여 Android 프로필을 벨소리, 진동 및 사일런스로 변경하는 앱을 만듭니다.
  2. 앱이 닫힌 후에도 앱이 백그라운드에서 실행되는지 확인하십시오.
  3. 센서를 계속해서 실행하면 배터리가 너무 많이 소모됩니다. 가능한 한 배터리 전력을 절약 할 수있는 무언가가 있습니까?

이미 NO : 1을 수행했으며 예상대로 작동하며, 2와 3 만 남았습니다. 어떤 것은 배경에서이 코드를 실행하는 가장 쉬운 방법이 될 것입니다 :이 같은 아이디어가 :

enter image description here

내가 시작하고 두 버튼을 사용하여 배경 서비스를 중지하고자합니다.

여기 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) { 

} 

}

+0

당신은 배경에서 실행됩니다 서비스를 사용할 수 있으며, 배터리 소비를 최적화 할 수 있도록 브로드 캐스트 리시버를 설정할 수 있습니다 .. –

+0

그을 추가 잊으 서비스를 시작하려면, 배경 기능을 수행해야합니다 서비스의 종류 및 종류를 사용하여 수행하십시오. –

+0

서비스 및 방송 수신기에 대한 자습서가 많이 있습니다. Google에 전송할 수 있습니다. –

답변

1

당신 확실히해야 사용자 서비스.

Android 사용자 인터페이스는 사용자 환경을 원활하게하기 위해 장기 실행 작업을 수행하도록 제한됩니다. 일반적으로 장기간 실행되는 작업은 인터넷에서 주기적으로 데이터를 다운로드하고, 여러 레코드를 데이터베이스에 저장하고, 파일 I/O를 수행하고, 전화 연락처 목록을 가져 오는 등의 작업이 될 수 있습니다. 이러한 장기 실행 작업의 경우 서비스가 대안입니다.

서비스는 백그라운드에서 장기 실행 작업을 수행하는 데 사용되는 응용 프로그램 구성 요소입니다. 서비스에는 사용자 인터페이스가 없으며 둘 다 직접 활동과 통신 할 수 없습니다. 서비스를 시작한 구성 요소가 삭제 된 경우에도 서비스는 백그라운드에서 무기한 실행될 수 있습니다. 일반적으로 서비스는 항상 단일 작업을 수행하고 의도 한 작업이 완료되면 자체적으로 중지됩니다. 서비스는 응용 프로그램 인스턴스의 주 스레드에서 실행됩니다. 자체 스레드를 만들지 않습니다. 서비스가 장기 실행 차단 조작을 수행 할 경우 ANR (Application Not Responding)이 발생할 수 있습니다. 따라서 서비스 내에서 새 스레드를 만들어야합니다.

서비스 클래스

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

+0

고맙습니다. 나는 이것을 시험해보고 그것이 예상대로 작동 하는지를보고 주석에서 알리게한다. –

+0

또 다른 질문 :이 서비스를 중지하는 방법? 애플리케이션을 명시했다고 가정하고 버튼을 사용하여 서비스 시작 그런 다음 애플리케이션을 완전히 닫았지만 서비스는 백그라운드에서 계속 실행 중입니다. 서비스를 어떻게 중지 할 수 있습니까? –

+0

서비스가 끝나면 stopSelf() 메서드를 호출하여 서비스를 중지해야합니다. 그러나 stopService() 메소드를 호출하여 직접 서비스를 중지 할 수도 있습니다. stopService 메소드를 호출하면 서비스에서 onDestroy() 콜백이 호출됩니다. 응용 프로그램에서 수행중인 작업을 수동으로 중지해야합니다. –

관련 문제