这是用于检查互联网连接的BroadcastReceiver
,它显示"没有互联网"我断开wifi时吐司两次。
InternetDetector
。java的
package com.hfad.evenit;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
/**
* Created by Vicky on 26-Sep-15.
*/
public class InternetDetector extends BroadcastReceiver {
public InternetDetector() {
}
@Override
public void onReceive(Context context, Intent intent) {
boolean isVisible = MyApplication.isActivityVisible();
try {
if (isVisible == true) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
// Check internet connection and accrding to state change the
// text of activity by calling method
if (networkInfo != null && networkInfo.isConnected())
{
Toast.makeText(context, "Internet Available", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(context, "No Internet", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hfad.evenit" >
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".EnterPhoneNumber"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name=".EnterVerificationCode"
android:label="@string/title_activity_enter_verification_code"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name=".GetNameAndEmail"
android:label="@string/title_activity_get_name_and_email"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateVisible" />
<activity
android:name=".Launcher"
android:label="@string/title_activity_launcher"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Home"
android:label="@string/app_name"
android:screenOrientation="portrait"
>
</activity>
<activity
android:name=".SettingsActivity"
android:label="@string/title_activity_settings"
android:screenOrientation="portrait">
</activity>
<receiver
android:name=".InternetDetector"
android:enabled="true" >
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
我尝试了几种解决方案,但似乎都没有。
答案 0 :(得分:5)
//scan the identified file to separate the different data streams
while(scCars.hasNextLine()){
index++;
scCars.useDelimiter(", ");
if(scCars.hasNext()){
//pull out the first string and set it as this car's make
make = scCars.next();
c.setMake(make);
//pull out the second string and set it as this car's model
model = scCars.next();
c.setModel(model);
//pull out the first int and set it as this car's year
year = scCars.nextInt();
c.setYear(year);
//pull out the first double and set it as this car's price
price = scCars.nextDouble();
c.setPrice(price);
//pull out the first boolean and set it as this car's happy
happy = scCars.nextBoolean();
c.setHappy(happy);
}
//add them all to the arraylist as this car object
c.carList.add(new CarA(c.getMake(), c.getModel(), c.getYear(), c.getPrice(), c.getHappy()));
}
scCars.close();
}
发送各种意图来通知不同的状态,所以这是正常的,你不是只捕捉互联网的开/关变化,这个功能不仅仅有这个选项,请参阅here更多细节。
UPD ,这是解决方案:
Exception in thread "AWT-EventQueue-0" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextBoolean(Scanner.java:1782)
at cara.CarGui.readFile(CarGui.java:256)
at cara.CarGui$1.actionPerformed(CarGui.java:191)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
答案 1 :(得分:2)
正如在Android文档中提到的那样,只要连接状态发生变化,当设备从移动数据移动到WIFI等时,就可以发送此广播。
对设备连接的更改可能非常频繁 - 每次在移动数据和Wi-Fi之间切换时都会触发此广播。
有很多州有关联,其中有一些可以找到in docs
要检查网络连接的当前状态,您应该使用getActiveNetworkInfo()。
所以检查状态的方法可能如下:
private void checkNetworkState(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo == null){
//no network
} else {
NetworkInfo.State state = activeNetworkInfo.getState();
switch (state){
case CONNECTED:
break;
case CONNECTING:
break;
case DISCONNECTED:
break;
case DISCONNECTING:
break;
case SUSPENDED:
break;
case UNKNOWN:
break;
}
}
}
请记住许可:android.Manifest.permission.ACCESS_NETWORK_STATE
答案 2 :(得分:0)
我想可以帮助这个。我更新了你的接收器。试试这肯定会帮助你。
package com.hfad.evenit;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
/**
* Created by Vicky on 26-Sep-15.
*/
public class InternetDetector extends BroadcastReceiver {
private boolean isConnected = false;
public InternetDetector() {
}
@Override
public void onReceive(Context context, Intent intent) {
boolean isVisible = MyApplication.isActivityVisible();
try {
if (isVisible == true) {
isNetworkAvailable(context);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if (!isConnected) {
Log.v(LOG_TAG, "Now you are connected to Internet!");
Toast.makeText(context, "Internet availablle via Broadcast receiver", Toast.LENGTH_SHORT).show();
isConnected = true;
// do your processing here ---
// if you need to post any data to the server or get
// status
// update from the server
}
return true;
}
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
Toast.makeText(context, "Internet NOT availablle via Broadcast receiver", Toast.LENGTH_SHORT).show();
isConnected = false;
return false;
}
}
答案 3 :(得分:0)
您需要声明变量b
以删除重复操作。
boolean b = true;
if(b){
// do something, in the first trigger
}else{
//do nothing, cancel trigger
}
b = !b;
答案 4 :(得分:0)
BroadcastReceiver ConnectivityReceiver =新的BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnectedToData;
final int currentType = activeNetwork != null
? activeNetwork.getType() : NO_CONNECTION_TYPE;
if (sLastType != currentType) {
if (activeNetwork != null) {
boolean isWiFi = ConnectivityManager.TYPE_WIFI == currentType;
boolean isMobile = ConnectivityManager.TYPE_MOBILE == currentType;
if (isWiFi || isMobile) {
boolean isConnected = activeNetwork.isConnectedOrConnecting();
if (isConnected) {
isConnectedToData = isConnected;
} else {
isConnectedToData = false;
}
} else {
isConnectedToData = false;
}
// TODO Connected. Do your stuff!
} else {
// TODO Disconnected. Do your stuff!
isConnectedToData = false;
}
sLastType = currentType;
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(isConnectedToData);
}
}
}
};