连接更改接收器不起作用?

Connection Change Receiver doesn't work?

首先,我使用的是 api 23 而不是 android N,所以 android.net.conn.CONNECTIVITY_CHANGE 应该对我仍然有效,但它没有。

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="enis.example.com.connectivitytest">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <receiver android:name="com.connectivitytest.ConnectionChangeReceiver"
            android:label="NetworkConnection">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

ConnectionChangeReceiver

package com.connectivitytest;

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.widget.Toast;


public class ConnectionChangeReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent )
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(     ConnectivityManager.TYPE_MOBILE );
        if ( activeNetInfo != null )
        {
            Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_LONG ).show();
                Log.v("Active Network Type : ", activeNetInfo.getTypeName());

        }
       if( mobNetInfo != null )
        {
            Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_LONG ).show();

        }                Log.v("Mobile Network Type : ", activeNetInfo.getTypeName());



    }
}

没有任何 toast 消息,所以我添加了日志消息只是为了清楚,但它也没有出现在 logcat 中。 我什至尝试了以下代码:https://gist.github.com/mjohnsullivan/1fec89187b1274dc256e 但都是一样的,没有错误但什么也没有发生,没有吐司消息也没有日志消息

I mean the whole point of having a receiver is to do things in the background, and now I run an activity in the foreground ?

用户需要运行您的activity一次,才能将您的应用移出so-called"stopped state"您的应用程序在安装后被放入。此后,您的接收器将按照您的预期工作,直到:

  • 用户卸载了您的应用,或者
  • 用户进入“设置”,在列表中找到您的应用,然后点击 "Force Stop" 按钮

在后一种情况下,您的应用将返回到停止状态,您的接收器将不再工作,直到用户再次启动您的 activity。

what if I don't need anything else except for the the tasks that should be ran when there is a network available ?

最有可能的是,用户想要配置您的应用行为的某些方面。而且,为此,用户将需要一个用户界面。

What do I write in the activity to begin with ?

如果不出意外,如果您打算在 Play 商店中发货,您将需要您的隐私政策。