检查INTENT互联网连接

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了检查INTENT互联网连接相关的知识,希望对你有一定的参考价值。

是否有android Intent ACTION_XXX在Internet连接可用时通知我?

我想实例化一个BroadcastReceiver,当用户启用Internet连接时(通过wifi,GSM等)通知我的应用程序

谁能帮助我?

答案
<receiver android:name=".YOURRECEIVER">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
另一答案
**Also worked on above Android 7.0**

// AndroidManifest.xml

 <service
            android:name=".NetworkSchedulerService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE"/>


// MyApplication.java           

import  android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
public class MyApplication extends Application {

    private static Context context;

    public static Context getContext() {
        return context;
    }

    public static final String TAG = MyApplication.class.getSimpleName();

    private static MyApplication mInstance;


    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        mInstance = this;
        scheduleJob();
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    private void scheduleJob()
    {
        JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
                .setRequiresCharging(true)
                .setMinimumLatency(1000)
                .setOverrideDeadline(2000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build();

        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        assert jobScheduler != null;
        jobScheduler.schedule(myJob);
    }
}   


// Constants.java   

public class Constants {
    public static final String CONNECT_TO_WIFI = "WIFI";
    public static final String CONNECT_TO_MOBILE = "MOBILE";
    public static final String NOT_CONNECT = "NOT_CONNECT";
    public final static String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
}


// LiveConnectivityReceiver.java    

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class LiveConnectivityReceiver extends BroadcastReceiver {

    private MConnectivityReceiver mConnectivityReceiver;
    LiveConnectivityReceiver(MConnectivityReceiver listener) {
        mConnectivityReceiver = listener;
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        mConnectivityReceiver.onNetworkConnectionChanged(isConnected(context));

    }

    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert cm != null;
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    public interface MConnectivityReceiver {
        void onNetworkConnectionChanged(boolean isConnected);
    }
}   


// MainActivity.java    

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    protected void onStop() {
        stopService(new Intent(this, NetworkSchedulerService.class));
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        startService( new Intent(this, NetworkSchedulerService.class));
    }


    @Override
    protected void onPause() {
        super.onPause();
        this.unregisterReceiver(this.mReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter("android.intent.action.MAIN");
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean isConnection = intent.getBooleanExtra("VALUE", false);
                if (!isConnection) {
                    Toast.makeText(context, "No Internet Connection", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Back to online", Toast.LENGTH_SHORT).show();
                }
            }
        };
        this.registerReceiver(mReceiver, intentFilter);
    }
}   


// NetworkSchedulerService.java 


import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.content.IntentFilter;

public class NetworkSchedulerService extends JobService implements LiveConnectivityReceiver.ConnectivityReceiverListener 
{

    private LiveConnectivityReceiver mLiveConnectivityReceiver;

    @Override
    public void onCreate()
    {
        super.onCreate();
        mLiveConnectivityReceiver = new LiveConnectivityReceiver(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        registerReceiver(mLiveConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        unregisterReceiver(mLiveConnectivityReceiver);
        return true;
    }

    @Override
    public void onNetworkConnectionChanged(boolean isConnected)
    {
        Intent broadcastedIntent=new Intent("android.intent.action.MAIN");
        broadcastedIntent.putExtra("VALUE", isConnected);
        sendBroadcast(broadcastedIntent);
    }
}
另一答案

From Android 7++, @fedj's answer will not work but you can register the broadcast receiver programmatically.

针对Android 7.0(API级别24)及更高版本的应用如果在其清单中声明广播接收器,则不会收到CONNECTIVITY_ACTION广播。如果应用程序使用Context.registerReceiver()注册其BroadcastReceiver并且该上下文仍然有效,则仍会收到CONNECTIVITY_ACTION广播。

另一答案

我会阅读为nougat +更新的文档,因为由于设备数量而不推荐使用intent,仅靠网络信息是不够的。我会在那里使用连接管理器(连接操作,在那里添加变量)命令和变量,因为大多数在去年仅发生了变化,并且在测试时,启用单元数据始终处于活动状态,详细记录和积极切换,如果需要,请使用wlan过滤器:

https://developer.android.com/reference/android/net/ConnectivityManager.html#CONNECTIVITY_ACTION

另一答案

接受的答案是正确的。我只添加了Receiver代码来完成:

public class NetworkStateReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
     Log.d("app","Network connectivity change");
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            Log.i("app","Network "+ni.getTypeName()+" connected");
        } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            Log.d("app","There's no network connectivity");
        }
   }
}
另一答案

更新@lujop回答:

public class NetworkStateRecei

以上是关于检查INTENT互联网连接的主要内容,如果未能解决你的问题,请参考以下文章

android根据互联网连接更改视图

无法找到包含 Intent 在片段中时的配置根

android小知识点代码片段

片段创建的 Intent 不会触发 onNewIntent

使用BroadcastReciever传递Intent.EXTRAS

没有带有拉动刷新的互联网消息 webview 片段