簡體   English   中英

每5分鍾重啟android后如何檢查互聯網連接?

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

您好我剛開始學習java,需要在重啟設備后檢查互聯網連接。 但重啟后出現錯誤我的代碼: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);
        }
    }

服務:

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;
    }

但重啟后我有消息:“YourApp 已停止!”

為此,您需要在清單文件中添加以下權限。

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

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM