0

下面是我的mainActivity类,并且我在Manifest文件中启用了 CHANGE_NETWORKSTATE、INTERNET、ACCESS_NETWORKSTATE 权限。

对于下面的代码,我测试了(当我按下按钮时没有任何反应

如果有人能在这里找出错误,非常感谢:)

注意:我的 wifi 应该在此之前和之后保持打开状态。

public class MainActivity extends AppCompatActivity {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.download);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Context context = getApplicationContext();
                NetworkRequest.Builder request = new NetworkRequest.Builder();
                request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
                request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
                ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                connectivityManager.requestNetwork(request.build(), new ConnectivityManager.NetworkCallback());

            }
        });
    }
}
4

0 回答 0