Hello I just start learn java, and need to check internet connection after reboot device. But after reboot has error My code: 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!"