2012-11-16 32 views
0

我做了一個應用程序來檢測我連接到哪個wifi,並基於這種改變無聲和無聲之間的聲音模式。不過,我懷疑,天氣我這樣做的方式是合理的。在Android中使用服務和廣播接收機「經濟」在我的Android

我已經把它作爲一種服務,因爲我希望它一直檢查。在服務裏面,我在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

只想說,這是一個應用一個真正偉大的想法。 –

+0

謝謝,只要我測試過,我可以把它放在商店裏! – gedemagt

+0

你介意分享結果代碼嗎? – memyself

回答

2

無需長時間運行的服務。

您可以在您的AndroidManifest中設置您的廣播接收器,並完成onReceive(Context context,Intent intent)方法的所有工作。

看看下面的文檔,以瞭解如何建立一個廣播接收器在AndroidManifest http://developer.android.com/guide/topics/manifest/receiver-element.html

+0

但是,如果我不提供服務,那麼它會做任何事情,如果應用程序不活躍?我的意思是,如果我安裝它,註冊一個網絡,關閉應用程序,然後我會在事件中做任何事情? – gedemagt

+2

如果您在Android Manifest上註冊BroadcastReceiver,則每次發生連接事件時都會調用接收器。您的應用程序無需一直在後臺「運行」,以便獲得該活動。 –