WiFi 断开时播放音乐

Play a music when WiFi is disconnected

我正在尝试为我的项目编写代码,以便在 WiFi 连接断开时播放音乐,并且每当用户单击 'test' 按钮时,它都会显示当前的连接强度。我试过以下代码:

主要 activity 部分(用于测试按钮并调出 class AlarmManagerBroadcastReceiver :

public class MainActivity extends FragmentActivity {

    public static final String TAG = "Final Year Project";
    private static boolean wifiConnected = false;
    private static boolean mobileConnected = false;

    private LogFragment mLogFragment;

    private AlarmManagerBroadcastReceiver alarm ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_main);


    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    registerReceiver(alarm, intentFilter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // When the user clicks TEST, display the connection status.
            case R.id.test_action:
                checkNetworkStrengh();
                return true;
            // Clear the log view fragment.
            case R.id.clear_action:
                mLogFragment.getLogView().setText("");
                return true;
        }
        return false;
    }

    private void checkNetworkStrengh() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo Info = cm.getActiveNetworkInfo();
        if (Info == null || !Info.isConnectedOrConnecting()) {
            Log.i(TAG, "No connection");
        } else {
            int netType = Info.getType();
            int netSubtype = Info.getSubtype();

            if (netType == ConnectivityManager.TYPE_WIFI) {
                Log.i(TAG, "Wifi connection");
                WifiManager wifiManager = (WifiManager) getApplication().getSystemService(Context.WIFI_SERVICE);
                List<ScanResult> scanResult = wifiManager.getScanResults();
                for (int i = 0; i < scanResult.size();) {
                    Log.d("scanResult", "Speed of wifi" + scanResult.get(i).level);//The db level of signal //

                       // its okay now thanks guys //    
                }


            } else if (netType == ConnectivityManager.TYPE_MOBILE) {

                Log.i(TAG, "GPRS/3G connection");

                // Need to get differentiate between 3G/GPRS
            }
        }
    }
}

AlarmManagerBroadcastReceiver部分(为了时刻扫描当前网络连接而创建):

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {

    private static boolean wifiConnected = false;
    private static boolean mobileConnected = false;

    @Override
    public void onReceive(Context context, Intent intent) {
            public void onReceive(Context context, Intent intent) {


    if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        NetworkInfo networkInfo =
                intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (networkInfo.isConnected()) {
            // Wifi is connected
            Intent in = new Intent(context, RingService.class);
            context.stopService(in);
        } else {
            Intent in = new Intent(context, RingService.class);
            context.startService(in);

        }
    }

}

和 MusicService 部分(为了在 class AlarmMAnagerBroadcastReceiver 触发特定条件时播放音乐而创建):

public class MusicService extends Service{

    private MediaPlayer mp;

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        mp.start();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                try {
                    mp.start();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            public boolean onError(MediaPlayer mp, int what, int extra) {
                // TODO Auto-generated method stub
          try {
                    mp.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }
        });

        super.onStart(intent, startId);
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        try {
            mp = new MediaPlayer();
            mp = MediaPlayer.create(MusicService.this, R.raw.ly);
            mp.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        super.onCreate();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        mp.stop();
        mp.release();
        super.onDestroy();
    }

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

}

清单文件

        <service
            android:name="com.example.android.basicnetworking.RingService"
            android:exported="true"
            android:process=":remote" >
        </service>
            
                    <receiver android:name=".AlarmManagerBroadcastReceiver" >
            <intent-filter android:priority="100" android:enabled="true"
                android:label="ConnectivityActionReceiver">
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.STATE_CHANGE" />
            </intent-filter>

        </receiver>

android 编程方面的专业人士能否帮助我编写代码,因为我是 android 和 java 编程方面的新手)让 return 来检查连接性 class 在 AlarmManagerBroadcastReceiver 部分,以及当 wifi 连接丢失时播放音乐。

编辑:感谢您的帮助。我想通了。如果有人需要代码,你可以给我发邮件,否则我会在一切正常后上传完整的代码。

编辑:更新了一些代码

WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int numberOfLevels = 5;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);

当你再次尝试播放音乐时,你需要重新准备,所以每次开始调用之前也要准备:

将此添加到 AlarmManagerBroadcastReceiver:

void play(int musicId) {
    MediaPlayer mp = MediaPlayer.create(getContext(), musicId);
    mp.prepare();
    mp.start();
}

并在您要播放音乐的 checkConnectivity 中:

play(R.raw.ly); // or use other resource instead of ly

断开连接时播放声音...试试这个:

       public class NetworkReceiver extends BroadcastReceiver {
            static boolean isConnect = false;

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "network changed");
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
                if (activeNetwork != null) { // connected to the internet
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                        Log.d(TAG, "network type wifi"); // connected on wifi

                    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                        Log.d(TAG, "network type mobile"); // connected on mobile (3g/4g)
                    }
                } else {
                    isConnect = false;
                    Log.d(TAG, "no connection"); // DISCONNECTED
                    playMySound(); // <- your play sound function
                }

            }

            public void playMySound() {
                MediaPlayer sound = MediaPlayer.create(context, R.raw.song);
                sound.start();
            }
       }