나는 어떤 무선 랜이 연결되어 있는지 감지하고 침묵과 무음 사이의 사운드 모드를 변경하는 앱을 만들었습니다. 나는 그것이 내가하고있는 길은 합리적이라고 생각한다.안드로이드에서 "경제적으로"경제적 인 서비스와 방송 수신기를 사용합니다.
항상 확인하고 싶기 때문에 서비스로 만들었습니다. 서비스 내에서 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);
}
}
AndroidManifest를 에 방송 수신기를 설정하는 방법을 알아 보려면 다음 문서에서 살펴 보자. –
감사합니다. 시험을 치르 자마자 매장에 넣을 수 있습니다! – gedemagt
결과 코드를 공유 하시겠습니까? – memyself