您的位置:首页 > 移动开发 > Android开发

Android——下载apk显示通知提示

2016-11-23 20:28 363 查看
应用到的知识点:广播 Receiver / Handler / 通知Notification

创建类:

MainActivity extends AppCompatActivity


MyService extends Service  //服务


InstallAPKUtils  //安装APK


SDCardHelper	//SD卡类


页面定义一个下载按钮<Button />

MainActivity:

private Button button;//控件
private String apkName="hello.apk";//apk名字
private String apkPath="http://218.244.149.129:9010/download.php?apkid=13";//apk下载路径

private boolean isDownLoad =false;

//初始化广播接受者
private MyReceiver receiver=new MyReceiver();

private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
button.setText("安装");
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.button);
//判断:下载的目录中,是否有该apk,有则显示"安装",没有显示"下载"
byte[] data=SDCardHelper.getBytePublicDir(apkName);
if(data!=null && data.length>0){
button.setText("安装");
}else {
button.setText("下载");
isDownLoad=true;
}

//注册广播接受者
IntentFilter filter=new IntentFilter();
filter.addAction("com.qf.downLoad");
registerReceiver(receiver,filter);

}

//点击下载/安装按钮
public void downLoad(View v){
if(isDownLoad){
//开启服务下载apk
Intent intent=new Intent(MainActivity.this,MyService.class);
intent.putExtra("apkName",apkName);
intent.putExtra("apkPath",apkPath);
startService(intent);
}else{
//安装apk
InstallAPKUtils.installApk(SDCardHelper.getFile(apkName),this);
}
}

/**
*自定义广播接受者
*/
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//给Handler 发送消息,改变按钮显示的内容
handler.sendEmptyMessage(1);
}
}


MyService:

private NotificationManager manager;

@Override
public void onCreate() {
super.onCreate();
manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
//1 获取传入的apkName apkPath
final String apkName=intent.getStringExtra("apkName");
final String apkPath=intent.getStringExtra("apkPath");

//2 根据apkPath开启线程下载
new Thread(){
@Override
public void run() {
try {
//构建通知
NotificationCompat.Builder builder=new NotificationCompat.Builder(MyService.this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("下载提示");
builder.setContentText("下载中...");
//开启网络  加载数据
URL url=new URL(apkPath);

HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if(conn.getResponseCode()==200){
//获取下载的总长度
int maxLen=conn.getContentLength();
//当前加载的长度
int curLen=0;

BufferedInputStream bis=new BufferedInputStream(conn.getInputStream());

//把获取的流,存入到SD卡中
//SDCardHelper.getFile 返回文件的路径+文件的名称 的路径
FileOutputStream fos=new FileOutputStream(SDCardHelper.getFile(apkName));

byte[] buff=new byte[1024];
int len=0;
while ((len=bis.read(buff))!=-1){
curLen+=len;

//计算当前下载的进度(百分比)
int progress=curLen*100/maxLen;

//把当前下载的进度值,通过通知发送出去
builder.setProgress(100,progress,false);
//发送通知
manager.notify(1,builder.build());
//Thread.sleep(2000);
//写出流
fos.write(buff,0,len);
}
fos.flush();
fos.close();
bis.close();
}
}catch (Exception e){
e.printStackTrace();
}
//移除下载通知
manager.cancel(1);

//发送下载成功的通知
NotificationCompat.Builder builder=new NotificationCompat.Builder(MyService.this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("提示");
builder.setContentText("下载完成");
builder.setTicker("下载完成");

manager.notify(2,builder.build());

//发送下载完成的广播
Intent intent=new Intent();
intent.setAction("com.qf.downLoad");
sendBroadcast(intent);

}
}.start();

return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent intent) {
return null;
}


InstalAPKUtils:

public static void installApk(File file, Context context)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

}


SDCardHelper:

//向sd卡中读取数据


public static byte[] getBytePublicDir(String fileName)
{
BufferedInputStream bis = null;
ByteArrayOutputStream baos =null;
try {
//1, 判断sd卡的状态
if(isMounted())
{
baos = new ByteArrayOutputStream();

File file = new File(PATH, fileName);

if(file.exists())//判断该图片是否存在
{
FileInputStream fis = new FileInputStream(file);

bis = new BufferedInputStream(fis);

byte[] buffer = new byte[1024];
int len = 0;

while ((len = bis.read(buffer))!=-1) {

baos.write(buffer, 0, len);
baos.flush();
}

return baos.toByteArray();
}
}
} catch (Exception e) {
// TODO: handle exception
}finally
{
if(bis!=null)
{
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(baos!=null)
{
try {
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**
* 返回文件的路径+文件的名称 的路径
*
*/
public static File getFile(String fileName)
{
File file = new File(PATH,fileName);

return file;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android apk
相关文章推荐