今天突然测试说app不能升级了,我看了看原来是我升级androidstuido,默认版本升级了,
索性就做个适配把,其实问题就俩个第一个是声音在NotificationChannel 中设置,不是在原来的
Notification中设置了,还有一个问题是在创建Notification前先把NotificationChannel创建出
来,还有一个问题是,升级app需要多添加一个权限,允许外来安装权限,好了就这么多。
public static final String ACTION_START = "ACTION_START";
private String mApkPath;
private String mApkName;
private boolean mCanceled = false;
private NotificationManager mManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onCreate() {
super.onCreate();
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
mApkPath = Environment.getExternalStorageDirectory().getAbsolutePath();
mApkName = "otouzi.apk";
initNotificationChannel(this);
setUpNotifiction();
registerBroader();
} else {
ToastUtils.getInstance(UpdateService2.this, "SD卡不存在",
Toast.LENGTH_SHORT).show();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (ACTION_START.equals(intent.getAction())) {// 下载跟新
NewVersion newVersion = (NewVersion) intent
.getSerializableExtra("Version");
// newVersion.url = "http://www.imooc.com/mobile/imooc.apk";// 测试
new Thread(new UpdateService2.DownApkRunnable(newVersion.url)).start();
}
return super.onStartCommand(intent, flags, startId);
}
/**
* 创建通知
* mNotification.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
* mNotification.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
* mNotification.setDefaults(Notification.DEFAULT_SOUND);
* Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
* Uri customSoundUri = Uri.parse(“android.resource://”+ getPackageName()+“/”+ R.raw.twirl)
*/
Notification.Builder mNotification;
RemoteViews contentView;
@RequiresApi(api = Build.VERSION_CODES.O)
private void setUpNotifiction() {
mManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
mNotification = new Notification.Builder(UpdateService2.this, "1");
mNotification.setSmallIcon(android.R.drawable.stat_notify_chat)
.setContentText("屹农金服")
.setNumber(3)
.setPriority(Notification.PRIORITY_MAX)
.setContentTitle("屹农金服");
// Uri customSoundUri=Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" +R.raw.twirl);
// mNotification.setSound(customSoundUri);//defaultSoundUri
contentView = new RemoteViews(getPackageName(),
R.layout.activity_notify_update);
contentView.setTextViewText(R.id.name, "正在下载中");
Intent canceledIntent = new Intent("canceled");
canceledIntent.putExtra("canceled", "canceled");
PendingIntent canceledPendingIntent = PendingIntent.getBroadcast(
UpdateService2.this, 1, canceledIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.cancle, canceledPendingIntent);
mNotification.setCustomContentView(contentView);
Intent intent = new Intent(UpdateService2.this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
UpdateService2.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mNotification.setContentIntent(contentIntent);
mManager.notify(0, mNotification.build());// 发送通知
}
/**
* 取消接收者
*
*
*/
class CanceledReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("canceled".equals(intent.getStringExtra("canceled"))) {
mCanceled = true;
mManager.cancel(0);
stopSelf();
}
}
}
/**
* 注册广播
*/
public void registerBroader() {
IntentFilter filter = new IntentFilter();
filter.addAction("canceled");
registerReceiver(new UpdateService2.CanceledReceiver(), filter);
}
/**
* 下载apk
*
*
*/
class DownApkRunnable implements Runnable {
private String mApkUrl;
public DownApkRunnable(String mApkUrl) {
super();
this.mApkUrl = mApkUrl;
}
@Override
public void run() {
downloadApk(mApkUrl);
}
}
private int laterate = 0;
/**
* 下载apk
*
* @param apkurl
*/
private void downloadApk(String apkurl) {
try {
URL url = new URL(apkurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int length = conn.getContentLength();
int count = 0;
File apkPathFile = new File(mApkPath);
if (!apkPathFile.exists()) {
apkPathFile.mkdir();
}
File apkFile = new File(mApkPath, mApkName);
InputStream in = conn.getInputStream();
FileOutputStream os = new FileOutputStream(apkFile);
byte[] buffer = new byte[1024];
do {
int numread = in.read(buffer);
count += numread;
int progress = (int) (((float) count / length) * 100);// 得到当前进度
if (progress >= laterate + 1) {// 只有当前进度比上一次进度大于等于1,才可以更新进度
laterate = progress;
Message msg = new Message();
msg.what = 1;
msg.arg1 = progress;
handler.sendMessage(msg);
}
if (numread <= 0) {// 下载完毕
handler.sendEmptyMessage(2);
mCanceled = true;
break;
}
os.write(buffer, 0, numread);
} while (!mCanceled);// 如果没有被取消
in.close();
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.toString();
e.printStackTrace();
}
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:// 更新进度
int progress = msg.arg1;
if (progress < 100) {
contentView.setTextViewText(R.id.tv_progress, progress
+ "%");
contentView.setProgressBar(R.id.progressbar, 100, progress,
false);
} else {// 下载完成,停止服务
stopSelf();
}
mManager.notify(0, mNotification.build());
break;
case 2:// 安装apk
mManager.cancel(0);
installApk();
break;
default:
break;
}
}
};
/**
* 安装apk
*/
private void installApk() {
File apkFile = new File(mApkPath,mApkName);
// File apkFile = new File("/storage/emulated/0/otouzi.apk");
if (!apkFile.exists()) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.otouzi.finance.fileprovider", apkFile);
Logger.d("contentUri: " + contentUri);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
}
startActivity(intent);
}
/**
* 初始化信息适配8.0
* @param context
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void initNotificationChannel(Context context) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel2 = new NotificationChannel("1",
"Channel2", NotificationManager.IMPORTANCE_DEFAULT);
// Uri customSoundUri=Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" +R.raw.twirl);
channel2.setSound(null,null);
channel2.enableLights(true);
channel2.setLightColor(Color.GREEN);
mNotificationManager.createNotificationChannel(channel2);
}
}
共同学习,写下你的评论
评论加载中...
作者其他优质文章