├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── me │ │ └── mrrobot97 │ │ └── netspeed │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── me │ │ │ └── mrrobot97 │ │ │ └── netspeed │ │ │ ├── MainActivity.java │ │ │ ├── MyBroadcastReceiver.java │ │ │ ├── MyTileService.java │ │ │ ├── SharedPreferencesUtils.java │ │ │ ├── SpeedCalculationService.java │ │ │ ├── SpeedView.java │ │ │ └── WindowUtil.java │ └── res │ │ ├── layout │ │ ├── activity_main.xml │ │ └── speed_layout.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── me │ └── mrrobot97 │ └── netspeed │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /README.md: -------------------------------------------------------------------------------- 1 | 先看下效果: 2 | 3 | ![demo](https://blog-1256554550.cos.ap-beijing.myqcloud.com/demo2.gif) 4 | 5 | 这里主要是在桌面上显示一个悬浮窗,利用了WindowManager以及Service,接下来看看如何实现这样一个效果: 6 | 首先APP必须获得在桌面上显示悬浮窗的机会,很多第三方ROM都限制了这一权限,我们首先就是要申请改权限,代码如下: 7 | 8 | ```java 9 | 10 | public boolean checkDrawOverlayPermission() { 11 | if (!Settings.canDrawOverlays(this)) { 12 | Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, 13 | Uri.parse("package:" + getPackageName())); 14 | startActivityForResult(intent, REQUEST_CODE); 15 | return false; 16 | } 17 | return true; 18 | } 19 | 20 | ``` 21 | 22 | 该函数首先检查APP是否有显示悬浮窗的权限,如果没有,就跳转到该APP设置悬浮窗权限的界面,如下图所示: 23 | 24 | ![](https://blog-1256554550.cos.ap-beijing.myqcloud.com/662ABA6C-D700-4CEC-A883-18714BCDBCEB.png) 25 | 26 | 然后先编写我们的悬浮窗,布局很简单,就是两个TextView: 27 | 28 | ```java 29 | 30 | 31 | 35 | 36 | 37 | 48 | 49 | 61 | 62 | 63 | ``` 64 | 65 | SpeedView: 66 | 67 | ```java 68 | 69 | public class SpeedView extends FrameLayout { 70 | private Context mContext; 71 | public TextView downText; 72 | public TextView upText; 73 | private WindowManager windowManager; 74 | private int statusBarHeight; 75 | private float preX,preY,x,y; 76 | 77 | public SpeedView(Context context) { 78 | super(context); 79 | mContext=context; 80 | init(); 81 | } 82 | 83 | private void init() { 84 | statusBarHeight=WindowUtil.statusBarHeight; 85 | windowManager= (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); 86 | //a view inflate itself, that's funny 87 | inflate(mContext,R.layout.speed_layout,this); 88 | downText= (TextView) findViewById(R.id.speed_down); 89 | upText= (TextView) findViewById(R.id.speed_up); 90 | } 91 | 92 | @Override 93 | public boolean onTouchEvent(MotionEvent event) { 94 | switch (event.getAction()){ 95 | case MotionEvent.ACTION_DOWN: 96 | preX=event.getRawX();preY=event.getRawY()-statusBarHeight; 97 | return true; 98 | case MotionEvent.ACTION_MOVE: 99 | x=event.getRawX();y=event.getRawY()-statusBarHeight; 100 | WindowManager.LayoutParams params= (WindowManager.LayoutParams) getLayoutParams(); 101 | params.x+=x-preX; 102 | params.y+=y-preY; 103 | windowManager.updateViewLayout(this,params); 104 | preX=x;preY=y; 105 | return true; 106 | default: 107 | break; 108 | 109 | } 110 | return super.onTouchEvent(event); 111 | } 112 | 113 | 114 | ``` 115 | 在SpeedView里我们重写了onTouchEvent事件,这样就能响应我们的拖拽事件了,注意这里更新SpeedView的位置是通过改变WindowManager.LayoutParam的x和y来实现的,调用`windowManager.updateViewLayout(this,params)`来更新位置。 116 | 117 | 因为我们的网速显示悬浮窗要脱离于Activity的生命周期而独立存在,因此需要通过Service来实现: 118 | 119 | ```java 120 | 121 | public class SpeedCalculationService extends Service { 122 | private WindowUtil windowUtil; 123 | private boolean changed=false; 124 | 125 | @Override 126 | public void onCreate() { 127 | super.onCreate(); 128 | WindowUtil.initX= (int) SharedPreferencesUtils.getFromSpfs(this,INIT_X,0); 129 | WindowUtil.initY= (int) SharedPreferencesUtils.getFromSpfs(this,INIT_Y,0); 130 | windowUtil=new WindowUtil(this); 131 | } 132 | 133 | @Override 134 | public int onStartCommand(Intent intent, int flags, int startId) { 135 | changed=intent.getBooleanExtra(MainActivity.CHANGED,false); 136 | if(changed){ 137 | windowUtil.onSettingChanged(); 138 | }else{ 139 | if(!windowUtil.isShowing()){ 140 | windowUtil.showSpeedView(); 141 | } 142 | SharedPreferencesUtils.putToSpfs(this,MainActivity.IS_SHOWN,true); 143 | } 144 | //return super.onStartCommand(intent, flags, startId); 145 | return START_STICKY; 146 | } 147 | 148 | 149 | 150 | @Nullable 151 | @Override 152 | public IBinder onBind(Intent intent) { 153 | return null; 154 | } 155 | 156 | @Override 157 | public void onDestroy() { 158 | super.onDestroy(); 159 | WindowManager.LayoutParams params= (WindowManager.LayoutParams) windowUtil.speedView.getLayoutParams(); 160 | SharedPreferencesUtils.putToSpfs(this, INIT_X,params.x); 161 | SharedPreferencesUtils.putToSpfs(this, INIT_Y,params.y); 162 | if(windowUtil.isShowing()){ 163 | windowUtil.closeSpeedView(); 164 | SharedPreferencesUtils.putToSpfs(this,MainActivity.IS_SHOWN,false); 165 | } 166 | Log.d("yjw","service destroy"); 167 | } 168 | } 169 | ``` 170 | 171 | 这里的WindowUtil其实就是一个工具类,帮助我们控制悬浮窗SpeedView的显示与隐藏: 172 | 173 | ```java 174 | 175 | public class WindowUtil { 176 | public static int statusBarHeight=0; 177 | //记录悬浮窗的位置 178 | public static int initX,initY; 179 | private WindowManager windowManager; 180 | public SpeedView speedView; 181 | private WindowManager.LayoutParams params; 182 | private Context context; 183 | 184 | public boolean isShowing() { 185 | return isShowing; 186 | } 187 | 188 | private boolean isShowing=false; 189 | 190 | public static final int INTERVAL=2000; 191 | private long preRxBytes,preSeBytes; 192 | private long rxBytes,seBytes; 193 | private Handler handler=new Handler(){ 194 | @Override 195 | public void dispatchMessage(Message msg) { 196 | super.dispatchMessage(msg); 197 | calculateNetSpeed(); 198 | sendEmptyMessageDelayed(0,INTERVAL); 199 | } 200 | }; 201 | 202 | public void onSettingChanged(){ 203 | String setting= (String) SharedPreferencesUtils.getFromSpfs(context,MainActivity.SETTING,MainActivity.BOTH); 204 | if(setting.equals(MainActivity.BOTH)){ 205 | speedView.upText.setVisibility(View.VISIBLE); 206 | speedView.downText.setVisibility(View.VISIBLE); 207 | }else if(setting.equals(MainActivity.UP)){ 208 | speedView.upText.setVisibility(View.VISIBLE); 209 | speedView.downText.setVisibility(View.GONE); 210 | }else{ 211 | speedView.upText.setVisibility(View.GONE); 212 | speedView.downText.setVisibility(View.VISIBLE); 213 | } 214 | } 215 | 216 | private void calculateNetSpeed() { 217 | rxBytes=TrafficStats.getTotalRxBytes(); 218 | seBytes=TrafficStats.getTotalTxBytes()-rxBytes; 219 | double downloadSpeed=(rxBytes-preRxBytes)/2; 220 | double uploadSpeed=(seBytes-preSeBytes)/2; 221 | preRxBytes=rxBytes; 222 | preSeBytes=seBytes; 223 | //根据范围决定显示单位 224 | String upSpeed=null; 225 | String downSpeed=null; 226 | 227 | NumberFormat df= java.text.NumberFormat.getNumberInstance(); 228 | df.setMaximumFractionDigits(2); 229 | 230 | if(downloadSpeed>1024*1024){ 231 | downloadSpeed/=(1024*1024); 232 | downSpeed=df.format(downloadSpeed)+"MB/s"; 233 | }else if(downloadSpeed>1024){ 234 | downloadSpeed/=(1024); 235 | downSpeed=df.format(downloadSpeed)+"B/s"; 236 | }else{ 237 | downSpeed=df.format(downloadSpeed)+"B/s"; 238 | } 239 | 240 | if(uploadSpeed>1024*1024){ 241 | uploadSpeed/=(1024*1024); 242 | upSpeed=df.format(uploadSpeed)+"MB/s"; 243 | }else if(uploadSpeed>1024){ 244 | uploadSpeed/=(1024); 245 | upSpeed=df.format(uploadSpeed)+"kB/s"; 246 | }else{ 247 | upSpeed=df.format(uploadSpeed)+"B/s"; 248 | } 249 | 250 | updateSpeed("↓ "+downSpeed,"↑ "+upSpeed); 251 | } 252 | 253 | public WindowUtil(Context context) { 254 | this.context = context; 255 | windowManager= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 256 | speedView=new SpeedView(context); 257 | params=new WindowManager.LayoutParams(); 258 | params=new WindowManager.LayoutParams(); 259 | params.x=initX; 260 | params.y=initY; 261 | params.width=params.height=WindowManager.LayoutParams.WRAP_CONTENT; 262 | params.type=WindowManager.LayoutParams.TYPE_PHONE; 263 | params.gravity= Gravity.LEFT|Gravity.TOP; 264 | params.format= PixelFormat.RGBA_8888; 265 | params.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; 266 | //设置悬浮窗可以拖拽至状态栏的位置 267 | // | WindowManager.LayoutParams.FLAG_FULLSCREEN| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; 268 | 269 | } 270 | 271 | public void showSpeedView(){ 272 | windowManager.addView(speedView,params); 273 | isShowing=true; 274 | preRxBytes= TrafficStats.getTotalRxBytes(); 275 | preSeBytes=TrafficStats.getTotalTxBytes()-preRxBytes; 276 | handler.sendEmptyMessage(0); 277 | } 278 | 279 | public void closeSpeedView(){ 280 | windowManager.removeView(speedView); 281 | isShowing=false; 282 | } 283 | 284 | public void updateSpeed(String downSpeed,String upSpeed){ 285 | speedView.upText.setText(upSpeed); 286 | speedView.downText.setText(downSpeed); 287 | } 288 | } 289 | 290 | ```java 291 | 292 | WindowUtil类中也包含了一个很重要的方法,那就是计算网速。这里计算网速的方法很简单,Android提供了一个类`TrafficStats`,这个类里面为我们提供了好多接口,我们用到了其中的两个: 293 | 294 | 1.public static long getTotalTxBytes () 295 | Return number of bytes transmitted since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage. 296 | 2.public static long getTotalRxPackets () 297 | Return number of packets received since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage. 298 | 299 | 300 | 可以看出,getTotalTxBytes()方法返回系统自开机到现在为止所一共传输的数据的字节数,包括上传的数据和下载的数据;而getTotalRxPackets()方法返回的是系统自开机到现在为止所一共接收到也就是下载的数据的字节数,用getTotalTxBytes()-getTotalRxPackets()自然就是系统开机到现在为止所上传的数据的字节数。 301 | 302 | 这样每隔一定时间,我们计算一下系统自开机到目前所接受的数据包的字节数和所发送的数据的字节数的变化量,用变化量除以时间,就是这段时间的平均网速了。 303 | 304 | 为了每个一段时间计算一下网速,我们利用了一个Handler来实现这个定时任务 305 | 306 | ```java 307 | 308 | private Handler handler=new Handler(){ 309 | @Override 310 | public void dispatchMessage(Message msg) { 311 | super.dispatchMessage(msg); 312 | calculateNetSpeed(); 313 | sendEmptyMessageDelayed(0,INTERVAL); 314 | } 315 | }; 316 | ``` 317 | 318 | 这里要注意将SpeedView添加到屏幕上,也就是添加到WindowManager里的时候,这个WindowManager.LayoutParams十分重要,其参数都是有用的,这里就不细讲了,详细介绍请移步[官方文档](https://developer.android.com/reference/android/view/WindowManager.LayoutParams.html). 319 | 320 | 最后要将我们的悬浮窗设置为开机自启动的,利用一个BroadcastReceiver就可以了: 321 | 322 | ```java 323 | 324 | public class MyBroadcastReceiver extends BroadcastReceiver { 325 | @Override 326 | public void onReceive(Context context, Intent intent) { 327 | Log.d("yjw","receiver receive boot broadcast"); 328 | boolean isShown= (boolean) SharedPreferencesUtils.getFromSpfs(context,MainActivity.IS_SHOWN,false); 329 | if(isShown){ 330 | context.startService(new Intent(context,SpeedCalculationService.class)); 331 | } 332 | } 333 | } 334 | ``` 335 | 在Manifest里这样注册我们的BroadcastReceiver: 336 | 337 | ```java 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | ``` 346 | 347 | 这样当系统启动完成,就会开启我们的Service。注意这里中的不可省略,亲测省略后BroadcastReceiver无法接收到系统广播。 348 | 349 | 最后还有一点,在Manifest的MainActivity条目中加一个属性:`android:excludeFromRecents="true"` 350 | 351 | 这样我们的ManiActivity就不会显示在最近任务列表,防止用户清空任务列表时将我们的Sercvice进程终结了。 352 | 353 | 完整的项目地址[Github](https://github.com/mrrobot97/NetSpeed) 354 | 355 | 356 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion "24.0.1" 6 | defaultConfig { 7 | applicationId "me.mrrobot97.netspeed" 8 | minSdkVersion 19 9 | targetSdkVersion 24 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | }) 27 | compile 'com.android.support:appcompat-v7:24.2.0' 28 | testCompile 'junit:junit:4.12' 29 | 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/mrrobot/Library/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/me/mrrobot97/netspeed/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package me.mrrobot97.netspeed; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("me.mrrobot97.netspeed", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 14 | 15 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /app/src/main/java/me/mrrobot97/netspeed/MainActivity.java: -------------------------------------------------------------------------------- 1 | package me.mrrobot97.netspeed; 2 | 3 | import android.content.Intent; 4 | import android.graphics.Rect; 5 | import android.net.Uri; 6 | import android.os.Build; 7 | import android.os.Bundle; 8 | import android.provider.Settings; 9 | import android.support.annotation.RequiresApi; 10 | import android.support.v7.app.AppCompatActivity; 11 | import android.view.View; 12 | import android.view.Window; 13 | import android.widget.Button; 14 | import android.widget.RadioButton; 15 | import android.widget.Toast; 16 | 17 | 18 | public class MainActivity extends AppCompatActivity { 19 | private int REQUEST_CODE=0; 20 | private Button showBt; 21 | private Button closeBt; 22 | private Button exitBt; 23 | private RadioButton radioBt1; 24 | private RadioButton radioBt2; 25 | private RadioButton radioBt3; 26 | 27 | public static final String SETTING="setting"; 28 | public static final String BOTH="both"; 29 | public static final String UP="up"; 30 | public static final String DOWN="down"; 31 | public static final String CHANGED="changed"; 32 | public static final String INIT_X="init_x"; 33 | public static final String INIT_Y="init_y"; 34 | public static final String IS_SHOWN="is_shown"; 35 | 36 | 37 | @RequiresApi(api = Build.VERSION_CODES.M) 38 | @Override 39 | protected void onCreate(Bundle savedInstanceState) { 40 | super.onCreate(savedInstanceState); 41 | setContentView(R.layout.activity_main); 42 | //检查悬浮窗权限 43 | if(checkDrawOverlayPermission()){ 44 | init(); 45 | } 46 | } 47 | 48 | private void init() { 49 | showBt= (Button) findViewById(R.id.bt_show); 50 | closeBt= (Button) findViewById(R.id.bt_close); 51 | exitBt= (Button) findViewById(R.id.bt_exit); 52 | radioBt1= (RadioButton) findViewById(R.id.radio_1); 53 | radioBt2= (RadioButton) findViewById(R.id.radio_2); 54 | radioBt3= (RadioButton) findViewById(R.id.radio_3); 55 | showBt.setOnClickListener(new View.OnClickListener() { 56 | @Override 57 | public void onClick(View view) { 58 | startService(new Intent(MainActivity.this,SpeedCalculationService.class)); 59 | } 60 | }); 61 | closeBt.setOnClickListener(new View.OnClickListener() { 62 | @Override 63 | public void onClick(View view) { 64 | stopService(new Intent(MainActivity.this,SpeedCalculationService.class)); 65 | } 66 | }); 67 | exitBt.setOnClickListener(new View.OnClickListener() { 68 | @Override 69 | public void onClick(View view) { 70 | finish(); 71 | } 72 | }); 73 | WindowUtil.statusBarHeight=getStatusBarHeight(); 74 | String setting= (String) SharedPreferencesUtils.getFromSpfs(this,SETTING,BOTH); 75 | if(setting.equals(BOTH)){ 76 | radioBt1.setChecked(true); 77 | }else if(setting.equals(UP)){ 78 | radioBt2.setChecked(true); 79 | }else{ 80 | radioBt3.setChecked(true); 81 | } 82 | } 83 | 84 | 85 | 86 | @RequiresApi(api = Build.VERSION_CODES.M) 87 | public boolean checkDrawOverlayPermission() { 88 | if (!Settings.canDrawOverlays(this)) { 89 | Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, 90 | Uri.parse("package:" + getPackageName())); 91 | startActivityForResult(intent, REQUEST_CODE); 92 | return false; 93 | } 94 | return true; 95 | } 96 | 97 | @RequiresApi(api = Build.VERSION_CODES.M) 98 | @Override 99 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 100 | super.onActivityResult(requestCode, resultCode, data); 101 | if(requestCode==REQUEST_CODE){ 102 | if (Settings.canDrawOverlays(this)) { 103 | init(); 104 | }else{ 105 | Toast.makeText(this, "请授予悬浮窗权限", Toast.LENGTH_SHORT).show(); 106 | finish(); 107 | } 108 | } 109 | } 110 | 111 | private int getStatusBarHeight(){ 112 | Rect rectangle = new Rect(); 113 | Window window =getWindow(); 114 | window.getDecorView().getWindowVisibleDisplayFrame(rectangle); 115 | int statusBarHeight = rectangle.top; 116 | return statusBarHeight; 117 | } 118 | 119 | public void onRadioButtonClick(View view){ 120 | switch (view.getId()){ 121 | case R.id.radio_1: 122 | radioBt1.setChecked(true); 123 | SharedPreferencesUtils.putToSpfs(this,SETTING,BOTH); 124 | break; 125 | case R.id.radio_2: 126 | radioBt2.setChecked(true); 127 | SharedPreferencesUtils.putToSpfs(this,SETTING,UP); 128 | break; 129 | case R.id.radio_3: 130 | radioBt3.setChecked(true); 131 | SharedPreferencesUtils.putToSpfs(this,SETTING,DOWN); 132 | break; 133 | default: 134 | break; 135 | } 136 | startService(new Intent(this,SpeedCalculationService.class) 137 | .putExtra(CHANGED,true)); 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /app/src/main/java/me/mrrobot97/netspeed/MyBroadcastReceiver.java: -------------------------------------------------------------------------------- 1 | package me.mrrobot97.netspeed; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.util.Log; 7 | 8 | /** 9 | * Created by mrrobot on 16/12/28. 10 | */ 11 | 12 | //开机自启动 13 | public class MyBroadcastReceiver extends BroadcastReceiver { 14 | @Override 15 | public void onReceive(Context context, Intent intent) { 16 | Log.d("yjw","receiver receive boot broadcast"); 17 | boolean isShown= (boolean) SharedPreferencesUtils.getFromSpfs(context,MainActivity.IS_SHOWN,false); 18 | if(isShown){ 19 | context.startService(new Intent(context,SpeedCalculationService.class)); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /app/src/main/java/me/mrrobot97/netspeed/MyTileService.java: -------------------------------------------------------------------------------- 1 | package me.mrrobot97.netspeed; 2 | 3 | import android.content.Intent; 4 | import android.os.Build; 5 | import android.service.quicksettings.TileService; 6 | import android.support.annotation.RequiresApi; 7 | 8 | /** 9 | * Created by mrrobot on 16/12/31. 10 | */ 11 | 12 | @RequiresApi(api = Build.VERSION_CODES.N) 13 | public class MyTileService extends TileService { 14 | @Override 15 | public void onClick() { 16 | super.onClick(); 17 | if(WindowUtil.isShowing){ 18 | stopService(new Intent(this,SpeedCalculationService.class)); 19 | }else{ 20 | startService(new Intent(this,SpeedCalculationService.class)); 21 | } 22 | 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/java/me/mrrobot97/netspeed/SharedPreferencesUtils.java: -------------------------------------------------------------------------------- 1 | package me.mrrobot97.netspeed; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | 6 | import java.util.Set; 7 | 8 | /** 9 | * Created by mrrobot on 16/12/28. 10 | */ 11 | 12 | public class SharedPreferencesUtils { 13 | public static String SHARED_FILE_NAME="spfs"; 14 | 15 | 16 | //sharedpreferences util 17 | public static void putToSpfs(Context context, String key, Object value){ 18 | SharedPreferences.Editor editor=context.getSharedPreferences(SHARED_FILE_NAME,Context.MODE_PRIVATE).edit(); 19 | if (value instanceof Integer){ 20 | editor.putInt(key, (Integer) value); 21 | }else if(value instanceof String){ 22 | editor.putString(key, (String) value); 23 | }else if(value instanceof Boolean){ 24 | editor.putBoolean(key, (Boolean) value); 25 | }else if(value instanceof Long){ 26 | editor.putLong(key, (Long) value); 27 | }else if(value instanceof Float){ 28 | editor.putFloat(key, (Float) value); 29 | }else if(value instanceof Set){ 30 | editor.putStringSet(key, (Set) value); 31 | } 32 | editor.apply(); 33 | } 34 | 35 | public static Object getFromSpfs(Context context,String key,Object defVal){ 36 | SharedPreferences spfs=context.getSharedPreferences(SHARED_FILE_NAME,Context.MODE_PRIVATE); 37 | if (defVal instanceof Integer){ 38 | return spfs.getInt(key, (Integer) defVal); 39 | }else if(defVal instanceof String){ 40 | return spfs.getString(key, (String) defVal); 41 | }else if(defVal instanceof Boolean){ 42 | return spfs.getBoolean(key, (Boolean) defVal); 43 | }else if(defVal instanceof Long){ 44 | return spfs.getLong(key, (Long) defVal); 45 | }else if(defVal instanceof Float){ 46 | return spfs.getFloat(key, (Float) defVal); 47 | }else if(defVal instanceof Set){ 48 | return spfs.getStringSet(key, (Set) defVal); 49 | } 50 | return null; 51 | } 52 | 53 | public static void removeInSpfs(Context context,String key){ 54 | SharedPreferences.Editor editor=context.getSharedPreferences(SHARED_FILE_NAME,Context.MODE_PRIVATE).edit(); 55 | editor.remove(key); 56 | editor.apply(); 57 | } 58 | 59 | public static void clearSpfs(Context context){ 60 | SharedPreferences.Editor editor=context.getSharedPreferences(SHARED_FILE_NAME,Context.MODE_PRIVATE).edit(); 61 | editor.clear(); 62 | editor.apply(); 63 | } 64 | 65 | } -------------------------------------------------------------------------------- /app/src/main/java/me/mrrobot97/netspeed/SpeedCalculationService.java: -------------------------------------------------------------------------------- 1 | package me.mrrobot97.netspeed; 2 | 3 | import android.app.Service; 4 | import android.content.Intent; 5 | import android.os.IBinder; 6 | import android.support.annotation.Nullable; 7 | import android.util.Log; 8 | import android.view.WindowManager; 9 | 10 | import static me.mrrobot97.netspeed.MainActivity.INIT_X; 11 | import static me.mrrobot97.netspeed.MainActivity.INIT_Y; 12 | 13 | /** 14 | * Created by mrrobot on 16/12/28. 15 | */ 16 | 17 | public class SpeedCalculationService extends Service { 18 | private WindowUtil windowUtil; 19 | private boolean changed=false; 20 | 21 | @Override 22 | public void onCreate() { 23 | super.onCreate(); 24 | WindowUtil.initX= (int) SharedPreferencesUtils.getFromSpfs(this,INIT_X,0); 25 | WindowUtil.initY= (int) SharedPreferencesUtils.getFromSpfs(this,INIT_Y,0); 26 | windowUtil=new WindowUtil(this); 27 | } 28 | 29 | @Override 30 | public int onStartCommand(Intent intent, int flags, int startId) { 31 | changed=intent.getBooleanExtra(MainActivity.CHANGED,false); 32 | if(changed){ 33 | windowUtil.onSettingChanged(); 34 | }else{ 35 | if(!windowUtil.isShowing()){ 36 | windowUtil.showSpeedView(); 37 | } 38 | SharedPreferencesUtils.putToSpfs(this,MainActivity.IS_SHOWN,true); 39 | } 40 | //return super.onStartCommand(intent, flags, startId); 41 | return START_STICKY; 42 | } 43 | 44 | 45 | 46 | @Nullable 47 | @Override 48 | public IBinder onBind(Intent intent) { 49 | return null; 50 | } 51 | 52 | @Override 53 | public void onDestroy() { 54 | super.onDestroy(); 55 | WindowManager.LayoutParams params= (WindowManager.LayoutParams) windowUtil.speedView.getLayoutParams(); 56 | SharedPreferencesUtils.putToSpfs(this, INIT_X,params.x); 57 | SharedPreferencesUtils.putToSpfs(this, INIT_Y,params.y); 58 | if(windowUtil.isShowing()){ 59 | windowUtil.closeSpeedView(); 60 | SharedPreferencesUtils.putToSpfs(this,MainActivity.IS_SHOWN,false); 61 | } 62 | Log.d("yjw","service destroy"); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /app/src/main/java/me/mrrobot97/netspeed/SpeedView.java: -------------------------------------------------------------------------------- 1 | package me.mrrobot97.netspeed; 2 | 3 | import android.content.Context; 4 | import android.view.MotionEvent; 5 | import android.view.WindowManager; 6 | import android.widget.FrameLayout; 7 | import android.widget.TextView; 8 | 9 | /** 10 | * Created by mrrobot on 16/12/28. 11 | */ 12 | 13 | public class SpeedView extends FrameLayout { 14 | private Context mContext; 15 | public TextView downText; 16 | public TextView upText; 17 | private WindowManager windowManager; 18 | private int statusBarHeight; 19 | private float preX,preY,x,y; 20 | 21 | public SpeedView(Context context) { 22 | super(context); 23 | mContext=context; 24 | init(); 25 | } 26 | 27 | private void init() { 28 | statusBarHeight=WindowUtil.statusBarHeight; 29 | windowManager= (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); 30 | //a view inflate itself, that's funny 31 | inflate(mContext,R.layout.speed_layout,this); 32 | downText= (TextView) findViewById(R.id.speed_down); 33 | upText= (TextView) findViewById(R.id.speed_up); 34 | } 35 | 36 | @Override 37 | public boolean onTouchEvent(MotionEvent event) { 38 | switch (event.getAction()){ 39 | case MotionEvent.ACTION_DOWN: 40 | preX=event.getRawX();preY=event.getRawY()-statusBarHeight; 41 | return true; 42 | case MotionEvent.ACTION_MOVE: 43 | x=event.getRawX();y=event.getRawY()-statusBarHeight; 44 | WindowManager.LayoutParams params= (WindowManager.LayoutParams) getLayoutParams(); 45 | params.x+=x-preX; 46 | params.y+=y-preY; 47 | windowManager.updateViewLayout(this,params); 48 | preX=x;preY=y; 49 | return true; 50 | default: 51 | break; 52 | 53 | } 54 | return super.onTouchEvent(event); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /app/src/main/java/me/mrrobot97/netspeed/WindowUtil.java: -------------------------------------------------------------------------------- 1 | package me.mrrobot97.netspeed; 2 | 3 | import android.content.Context; 4 | import android.graphics.PixelFormat; 5 | import android.net.TrafficStats; 6 | import android.os.Handler; 7 | import android.os.Message; 8 | import android.view.Gravity; 9 | import android.view.View; 10 | import android.view.WindowManager; 11 | 12 | import java.text.NumberFormat; 13 | 14 | /** 15 | * Created by mrrobot on 16/12/28. 16 | */ 17 | 18 | public class WindowUtil { 19 | public static int statusBarHeight=0; 20 | //记录悬浮窗的位置 21 | public static int initX,initY; 22 | private WindowManager windowManager; 23 | public SpeedView speedView; 24 | private WindowManager.LayoutParams params; 25 | private Context context; 26 | 27 | public boolean isShowing() { 28 | return isShowing; 29 | } 30 | 31 | public static boolean isShowing=false; 32 | 33 | public static final int INTERVAL=2000; 34 | private long preRxBytes,preSeBytes; 35 | private long rxBytes,seBytes; 36 | private Handler handler=new Handler(){ 37 | @Override 38 | public void dispatchMessage(Message msg) { 39 | super.dispatchMessage(msg); 40 | calculateNetSpeed(); 41 | sendEmptyMessageDelayed(0,INTERVAL); 42 | } 43 | }; 44 | 45 | public void onSettingChanged(){ 46 | String setting= (String) SharedPreferencesUtils.getFromSpfs(context,MainActivity.SETTING,MainActivity.BOTH); 47 | if(setting.equals(MainActivity.BOTH)){ 48 | speedView.upText.setVisibility(View.VISIBLE); 49 | speedView.downText.setVisibility(View.VISIBLE); 50 | }else if(setting.equals(MainActivity.UP)){ 51 | speedView.upText.setVisibility(View.VISIBLE); 52 | speedView.downText.setVisibility(View.GONE); 53 | }else{ 54 | speedView.upText.setVisibility(View.GONE); 55 | speedView.downText.setVisibility(View.VISIBLE); 56 | } 57 | } 58 | 59 | private void calculateNetSpeed() { 60 | rxBytes=TrafficStats.getTotalRxBytes(); 61 | seBytes=TrafficStats.getTotalTxBytes()-rxBytes; 62 | double downloadSpeed=(rxBytes-preRxBytes)/2; 63 | double uploadSpeed=(seBytes-preSeBytes)/2; 64 | preRxBytes=rxBytes; 65 | preSeBytes=seBytes; 66 | //根据范围决定显示单位 67 | String upSpeed=null; 68 | String downSpeed=null; 69 | 70 | NumberFormat df= java.text.NumberFormat.getNumberInstance(); 71 | df.setMaximumFractionDigits(2); 72 | 73 | if(downloadSpeed>1024*1024){ 74 | downloadSpeed/=(1024*1024); 75 | downSpeed=df.format(downloadSpeed)+"MB/s"; 76 | }else if(downloadSpeed>1024){ 77 | downloadSpeed/=(1024); 78 | downSpeed=df.format(downloadSpeed)+"KB/s"; 79 | }else{ 80 | downSpeed=df.format(downloadSpeed)+"B/s"; 81 | } 82 | 83 | if(uploadSpeed>1024*1024){ 84 | uploadSpeed/=(1024*1024); 85 | upSpeed=df.format(uploadSpeed)+"MB/s"; 86 | }else if(uploadSpeed>1024){ 87 | uploadSpeed/=(1024); 88 | upSpeed=df.format(uploadSpeed)+"KB/s"; 89 | }else{ 90 | upSpeed=df.format(uploadSpeed)+"B/s"; 91 | } 92 | 93 | updateSpeed("↓ "+downSpeed,"↑ "+upSpeed); 94 | } 95 | 96 | public WindowUtil(Context context) { 97 | this.context = context; 98 | windowManager= (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); 99 | speedView=new SpeedView(context); 100 | params=new WindowManager.LayoutParams(); 101 | params=new WindowManager.LayoutParams(); 102 | params.x=initX; 103 | params.y=initY; 104 | params.width=params.height=WindowManager.LayoutParams.WRAP_CONTENT; 105 | params.type=WindowManager.LayoutParams.TYPE_PHONE; 106 | params.gravity= Gravity.LEFT|Gravity.TOP; 107 | params.format= PixelFormat.RGBA_8888; 108 | params.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; 109 | //设置悬浮窗可以拖拽至状态栏的位置 110 | // | WindowManager.LayoutParams.FLAG_FULLSCREEN| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; 111 | 112 | } 113 | 114 | public void showSpeedView(){ 115 | windowManager.addView(speedView,params); 116 | isShowing=true; 117 | preRxBytes= TrafficStats.getTotalRxBytes(); 118 | preSeBytes=TrafficStats.getTotalTxBytes()-preRxBytes; 119 | handler.sendEmptyMessage(0); 120 | } 121 | 122 | public void closeSpeedView(){ 123 | windowManager.removeView(speedView); 124 | isShowing=false; 125 | } 126 | 127 | public void updateSpeed(String downSpeed,String upSpeed){ 128 | speedView.upText.setText(upSpeed); 129 | speedView.downText.setText(downSpeed); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 |