2012-11-16 5 views
0

나는 어떤 무선 랜이 연결되어 있는지 감지하고 침묵과 무음 사이의 사운드 모드를 변경하는 앱을 만들었습니다. 나는 그것이 내가하고있는 길은 합리적이라고 생각한다.안드로이드에서 "경제적으로"경제적 인 서비스와 방송 수신기를 사용합니다.

항상 확인하고 싶기 때문에 서비스로 만들었습니다. 서비스 내에서 onStartCommand() - 메소드에 브로드 캐스트 리시버를 등록하고 onDestroy()에서 등록을 등록 취소합니다. 그것은 구속력이 없습니다. 브로드 캐스트 수신기는 연결 변경을 수신 대기합니다.

나의 실제적인 질문은 이것이 이것을하는 "경제적으로"좋은 방법일까요? 아니면 서비스가 실행 중일 때 모든 배터리/메모리를 사용합니까? 서비스에 대한

내 (관련) 소스 코드 :

import java.util.ArrayList; 
import java.util.List; 

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.OnSharedPreferenceChangeListener; 
import android.media.AudioManager; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.net.wifi.WifiManager; 
import android.os.IBinder; 
import android.os.Vibrator; 
import android.util.Log; 
import android.widget.Toast; 

public class CheckService extends Service { 

public static final String MY_SETTINGS = "MySettings"; 
private ConnectivityReceiver receiver = null; 
public static boolean isRunning = false; 
private WifiManager wifi; 
private AudioManager audio_mngr; 
private SharedPreferences settings; 
private List<Network> networks; 
private String SSID; 


@Override 
public IBinder onBind(Intent arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
    receiver = new ConnectivityReceiver(); 
    wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
    audio_mngr = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE); 
    settings = getSharedPreferences(MY_SETTINGS, 0); 
    networks = getAllNetworks(); 
    settings.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener(){ 

     public void onSharedPreferenceChanged(
       SharedPreferences sharedPreferences, String key) { 
      networks = getAllNetworks(); 
     } 
    }); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    super.onStartCommand(intent, flags, startId); 
    registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 
    isRunning = true; 
    return START_STICKY; 
} 

@Override 
public void onDestroy() 
{ 
    super.onDestroy(); 

    //Stop the Background thread 
    isRunning = false; 
    unregisterReceiver(receiver); 

    //Announcement about stopping 
    Toast.makeText(this, "Stopping the Demo Service", Toast.LENGTH_SHORT).show(); 
} 

public List<Network> getAllNetworks() { 
    List<Network> temp = new ArrayList<Network>(); 
    String[] data = settings.getString("networks", "").split(","); 
    if(data.length>1) 
    { 
     for(int i=1; i<data.length-1; i+=2) 
     { 
      temp.add(new Network(data[i],data[i+1])); 
     } 
    } 
    return temp; 
} 

private class ConnectivityReceiver extends BroadcastReceiver{ 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); 
     if(null != info) 
     { 
      if(info.getState()==NetworkInfo.State.CONNECTED) 
      { 
       SSID = wifi.getConnectionInfo().getSSID(); 
       for(Network n : networks) 
       { 
        if(n.getSSID().equals(SSID)) 
        { 
         if(n.isQuiet()) setQuiet(); 
         else setLoud(); 
         break; 
        } 
       } 
      } 
     } 
    } 
} 

private void setQuiet() 
{ 
     Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
     audio_mngr .setRingerMode(AudioManager.RINGER_MODE_VIBRATE); 
     v.vibrate(300); 
     makeNotification(SSID,"Vibrate mode on!",R.drawable.sound_off); 
} 

private void setLoud() 
{ 
     Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
     audio_mngr .setRingerMode(AudioManager.RINGER_MODE_NORMAL); 
     v.vibrate(300); 
     makeNotification(SSID,"Normal mode on!", R.drawable.sound_on); 
} 

private void makeNotification(String network, String loudness, int icon) 
{ 
    NotificationManager notificationManager = (NotificationManager) 
       getSystemService(NOTIFICATION_SERVICE); 

    CharSequence tickerText = "Mode has been changed!"; 
    long when = System.currentTimeMillis(); 

    final Notification notification = new Notification(icon, tickerText, when); 

    Context context = getApplicationContext(); 
    CharSequence contentTitle = network; 
    CharSequence contentText = loudness; 
    Intent notificationIntent = new Intent(this, CheckService.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 

    final int HELLO_ID = 1; 

    notification.flags |= Notification.FLAG_AUTO_CANCEL; 
    notificationManager.notify(HELLO_ID, notification); 

} 
} 
+0

AndroidManifest를 에 방송 수신기를 설정하는 방법을 알아 보려면 다음 문서에서 살펴 보자. –

+0

감사합니다. 시험을 치르 자마자 매장에 넣을 수 있습니다! – gedemagt

+0

결과 코드를 공유 하시겠습니까? – memyself

답변

2

장기 실행 서비스에 대한 필요가 없습니다.

AndroidManifest에서 브로드 캐스트 수신기를 설정하고 onReceive (Context context, Intent intent) 메소드에서 모든 작업을 수행 할 수 있습니다.

그냥 그 응용 프로그램에 대한 정말 좋은 아이디어라고하고 싶었다 http://developer.android.com/guide/topics/manifest/receiver-element.html

+0

하지만 서비스를 만들지 않으면 앱이 활성화되어 있지 않으면 아무 것도하지 않겠습니까? 내 말은, 만약 내가 그것을 설치, 네트워크 등록, 응용 프로그램을 닫습니다, 그때 나는 이벤트에서 아무것도할까요? – gedemagt

+2

Android Manifest에 BroadcastReceiver를 등록하면 연결 이벤트가 발생할 때마다 수신자가 호출됩니다. 앱을 항상 배경에서 '실행'하지 않아도 이벤트를 가져올 수 있습니다. –

관련 문제