最近做的一个小demo,启动Service并在Service里面创建一个线程来监听下载进度,更新notification的UI。当然,demo里面的下载并非是真正的下载文件,而是一个循环累加的数值,有兴趣的朋友可以添加真正的下载线程来调试。Demo做得比较简单,没有设置点击响应事件,所以是没有取消下载的,只能算是个小demo吧,有机会时再实现更多功能。
MainActivity.java
Activity只有一个点击响应事件,点击service按钮时,将启动MyService,因为没实现交互,所以没有bindService。
package com.example.demo;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Button serviceButton = (Button)findViewById(R.id.button2);
serviceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyService.java
package com.example.demo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
public class MyService extends Service {
public MyService() {
}
private NotificationCompat.Builder nBuilder = null;
private Notification notification = null;
private NotificationManager manager = null;
private RemoteViews remoteViews = null;
private Handler sHandler = new Handler(){
@Override
public void handleMessage(Message message){
switch (message.what){
case 100:
manager.cancel(1);
stopSelf();
break;
default:
remoteViews.setProgressBar(R.id.progress, 100, message.what, false);
remoteViews.setTextViewText(R.id.progressText, Integer.toString(message.what)+"%");
manager.notify(1,notification);
break;
}
}
};
@Override
public void onCreate() {
super.onCreate();
nBuilder = new NotificationCompat.Builder(this);
nBuilder.setSmallIcon(R.mipmap.ic_launcher);
remoteViews = new RemoteViews(getApplication().getPackageName(), R.layout.layout_update_download);
nBuilder.setContent(remoteViews);
remoteViews.setProgressBar(R.id.progress, 100, 0, false);
remoteViews.setTextViewText(R.id.progressText, "0%");
notification = nBuilder.build();
Log.e("S","C");
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
private boolean buttonStatus = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("S", "S");
manager.notify(1, notification);
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
Message message = new Message();
message.what = i;
sHandler.sendMessage(message);
}
}
}).start();
return START_STICKY;
}
@Override
public void onDestroy() {
Log.e("S","D");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
Notification 布局文件
layout_update_download.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
<TextView
android:text="Download Update"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TextView>
<LinearLayout
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:id="@+id/progress"
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dp">
</ProgressBar>
<TextView
android:text="0%"
android:gravity="center"
android:layout_weight="5"
android:id="@+id/progressText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
演示
(请忽略里面的JUMP按钮)
点击service,开启“下载”