我必须在设备连接到互联网时显示通知 我是否需要一直为此服务?
答案 0 :(得分:1)
ConnectivityReceiver.java
public class ConnectivityReceiver
extends BroadcastReceiver {
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
}
}
public static boolean isConnected() {
ConnectivityManager
cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}}
MyApplication.java
public class MyApplication extends Application {
private static MyApplication mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}}
的AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".MyApplication"
android:allowBackup="true"
...
<receiver
android:name=".ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
...
</application>
Activity.class
public class MainActivity extends AppCompatActivity
implements ConnectivityReceiver.ConnectivityReceiverListener {
...
@Override
protected void onResume() {
super.onResume();
// register connection status listener
MyApplication.getInstance().setConnectivityListener(this);
}
...
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
if(isConnected){
Toast.makeText(context, "Internet Connected", Toast.LENGTH_SHORT).show();
}else{Toast.makeText(context, "Internet not Connected", Toast.LENGTH_SHORT).show();}
}}
答案 1 :(得分:0)
您需要广播接收器才能接收网络状态更改,然后将此数据传递给不是绑定服务的服务并创建通知,或者您可以在广播接收器中创建通知。
答案 2 :(得分:0)
您不必运行服务来检查连接更改。
您可以使用android.net.conn.CONNECTIVITY_CHANGE
意图注册广播接收器。
请注意
针对Android 7.0(API级别24)及更高版本的应用无法接收 这个广播,如果他们宣布广播接收器在他们的 表现。如果应用程序注册,他们仍会收到广播 带有Context.registerReceiver()的BroadcastReceiver和那个上下文是 仍然有效。
链接了解更多信息: https://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION