简体   繁体   English

每5分钟重启android后如何检查互联网连接?

[英]How to check internet connection after reboot android every 5min?

Hello I just start learn java, and need to check internet connection after reboot device.您好我刚开始学习java,需要在重启设备后检查互联网连接。 But after reboot has error My code: BroadcastReceiver:但重启后出现错误我的代码:BroadcastReceiver:

public class MainBroadcastReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
           MainService.startService(context);
        }
    }

Service:服务:

public class MainService extends Service {

public static void startService(Context context) {
        context.startService(new Intent(context, MainService.class));
    }

    Handler handler;
    Runnable test;
    public MainService() {
        handler = new Handler();
        test = new Runnable() {
            @Override
            public void run() {
                qqq();
                handler.postDelayed(test, 300000); // 5min
            }
        };

        handler.postDelayed(test, 100);
    }

            public void qqq() {
                // Check for Internet Connection
                if (isConnected()) {
                   Toast.makeText(getApplicationContext(), "Internet Connected", Toast.LENGTH_SHORT).show();
                } else {
                  Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
                }
            }

public boolean isConnected() {
        boolean connected = false;
        try {
            ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo nInfo = cm.getActiveNetworkInfo();
            connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
            return connected;
        } catch (Exception e) {
            Log.e("Connectivity Exception", e.getMessage());
        }
        return connected;
    }

But after reboot I have messege: "YourApp has stopped!"但重启后我有消息:“YourApp 已停止!”

For this to work, you need to add following permission in your manifest file.为此,您需要在清单文件中添加以下权限。

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM