问题描述
我正在使用广播接收器来监控网络变化。我想根据接收器状态的变化通过 webView 将网络状态发送到后端。但是 webView 在一个 Activity 中,而broadcast 是单独的类,以使其成为应用程序级别的监控。如何将数据从该接收器发送到 Activity 以在后端更新它?
广播接收器
public class NetworkChangeReceiver extends broadcastReceiver {
////"isOffline"
boolean mIsConnected = false;
public static final String broADCAST = "android.net.conn.CONNECTIVITY_CHANGE";
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onReceive(final Context context,final Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
new InternetSpeedTest(context).execute("sampleURL");
}
}
private class InternetSpeedTest
extends AsyncTask<String,Void,String> {
long startTime;
long endTime;
private long takenTime;
Context context;
public InternetSpeedTest(Context context) {
this.context =context;
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected String doInBackground(String... paramVarargs) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (cm == null || capabilities == null) {
return null;
}
else if ( capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
startTime = System.currentTimeMillis();
Log.d("TAG","doInBackground: StartTime" + startTime);
Bitmap bmp = null;
try {
URL ulrn = new URL(paramVarargs[0]);
HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
Bitmap bitmap = bmp;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,99,stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length;
if (null != bmp) {
endTime = System.currentTimeMillis();
Log.d("TAG","doInBackground: EndTIme" + endTime);
return lengthbmp + "";
}
} catch (Exception e) {
e.printstacktrace();
}
}
return null;
}
protected void onPostExecute(String result) {
if (result != null) {
long dataSize = Integer.parseInt(result) / 1024;
takenTime = endTime - startTime;
double s = (double) takenTime / 1000;
double speed = dataSize / s;
mIsConnected =true;
Log.d("TAG","onPostExecute: " + "" + new DecimalFormat("##.##").format(speed) + "kb/second");
//context.sendbroadcast(new Intent(broADCAST));
}
}
}
}
和活动中的webView更新代码类似
mWebview.evaluateJavascript("common.setofflinestatus(" + statusfromreceiver + ")",null);
如何将数据从该接收器发送到 Activity 以在后端更新它?
请帮我解决这个问题。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)