Android – close the application from the broadcast receiver

I'm new to Android programming. I've tried to register a broadcast receiver in the activity, but my receiver doesn't work properly when the application onpause. So I found that I need to register my receiver in the list

My goal is to close my application for a period of time after the user closes WiFi

This is my code, but it doesn't work

public class ReceiverWifi extends BroadcastReceiver {

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

        Handler handler = new Handler();
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                MainActivity m = new MainActivity();
                m.finish();

            }
        };

        if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {

            int newWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
                    WifiManager.WIFI_STATE_UNKNowN);

            switch (newWifiState) {

            case WifiManager.WIFI_STATE_DISABLED:

                Toast.makeText(context, "Wi-fi Disconnected ",
                        Toast.LENGTH_SHORT).show();

                handler.postDelayed(runnable, 15 * 1000);
                break;

            }
        }

    }
}

My list:

<receiver android:name="com.example.wifimonitor.ReceiverWifi" >
    <intent-filter>
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

How do I achieve my goals?

resolvent:

Is your broadcast receiver in the main activity class? If so, you can save the application's global context and turn it off later in the broadcast receiver

If it is on a service or provider, just send it an application instance at startup / registration, and then call finish () from that instance

Edit:

Try this:

Create this public method in your main activity:

   public static void closeActivity(){
        finish();
   }

Then call this method in your broadcast receiver, such as:

   MainActivity.closeActivity();

I hope I can help you

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>