发表于: 2018-10-25 22:44:12

2 638


一、今天完成的事情

Service和Notification基础

     学习了Service和Notification的基础知识,完成了一个简单的下载功能。

             

 Notification(通知)

    创建通知:

    获取一个NotificationManager来管理通知

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    使用Builder构造器创建一个Notification对象,这里面涉及到版本问题,如果Build.VERSION.SDK_INT >= 26,需要额外设置NotificationChannel

case R.id.bt_send_notification:
//创建一条通知并发送出去
   NotificationManager manager = (NotificationManager) getSystemService(
       NOTIFICATION_SERVICE);
   NotificationCompat.Builder mBuilder;
   //如果targetSdkVersion >= 26,需要创建Channel
   if (Build.VERSION.SDK_INT >= 26) {
       NotificationChannel channel = new NotificationChannel("default",
               "defaultChannel", NotificationManager.IMPORTANCE_DEFAULT);
       //长按图标时是否显示通知内容
       channel.setShowBadge(true);
       manager.createNotificationChannel(channel);
       //需要传入ChannelId
       mBuilder = new NotificationCompat.Builder(this, "default");
   } else {
       //targetSdkVersion < 26,不需要创建Channel
       mBuilder = new NotificationCompat.Builder(this);
   }
       Notification notification = mBuilder
           .setContentTitle("标题(测试)") //设置通知标题
           .setContentText("内容(测试)") //设置通知内容
           .setWhen(System.currentTimeMillis()) //设置通知时间,这是获取了当前系统时间
           .setSmallIcon(R.drawable.android_white_18dp) //设置通知图标(系统状态栏上显示的小图标)
           .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                   R.drawable.android_white_24dp)) //设置通知图标(下拉系统状态栏时显示的图标)
           .setLights(Color.GREEN, 1000, 1000)//设置呼吸灯
           .build();
   manager.notify(1, notification) ;
   break;

      最后调用NotificationManager的notify()方法将通知显示出来,这个方法有两个参数

      第一个参数是id,需要保证每个通知的id都不一样;

      第二个参数是Notification对象,可以用setContentTitle()、setContentText()等方法为其设置标题、内容等,方法有很多。

 

 

Service(服务)和下载

    Service是实现Android程序后台运行的解决方案,适合执行一些不需要与用户交互且长期运行的任务,比如下载、后台播放音乐等。

     服务中有这么几个方法:

    onCreate()    在服务创建时被调用

    onStartCommand()    在每次服务启动时被调用

    onDestory()    在服务销毁时被调用

     onBind()    绑定服务和活动

public class DownloadService extends Service {

private DownloadTask downloadTask;

   private String downloadUrl;

   private DownloadListener listener = new DownloadListener() {
       @Override
       public void onProgress(int progress) {
           getNotificationManager().notify(1, getNotification("Downloading...", progress));
       }

       @Override
       public void onSuccess() {
           downloadTask = null;
           stopForeground(true);
           getNotificationManager().notify(1, getNotification("下载成功", -1));
           Toast.makeText(DownloadService.this, "下载成功", Toast.LENGTH_SHORT).show();
       }

       @Override
       public void onFailed() {
           downloadTask = null;
           stopForeground(true);
           getNotificationManager().notify(1, getNotification("下载失败", -1));
           Toast.makeText(DownloadService.this, "下载失败", Toast.LENGTH_SHORT).show();
       }

       @Override
       public void onPaused() {
           downloadTask = null;
           Toast.makeText(DownloadService.this, "下载暂停", Toast.LENGTH_SHORT).show();
       }

       @Override
       public void onCanceled() {
           downloadTask = null;
           stopForeground(true);
           Toast.makeText(DownloadService.this, "下载取消", Toast.LENGTH_SHORT).show();
       }
};

   private DownloadBinder mBinder = new DownloadBinder();

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

    public class DownloadBinder extends Binder {
       public void startDowmload(String url) {
           if (downloadTask == null) {
               downloadUrl = url;
               downloadTask = new DownloadTask(listener);
               downloadTask.execute(downloadUrl);
               startForeground(1, getNotification("Download...", 0));
               Toast.makeText(DownloadService.this, "正在下载", Toast.LENGTH_SHORT).show();
           }
       }

       public void pauseDownload() {
           if (downloadTask != null) {
                downloadTask.pauseDownload();
           }
       }

       public void cancelDownload() {
           if (downloadTask != null) {
                downloadTask.cancelDownload();
           } else {
                if (downloadUrl != null) {
                   String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
                   String directory = Environment.getExternalStoragePublicDirectory(
                   Environment.DIRECTORY_DOWNLOADS).getPath();
                   File file = new File(directory + fileName);
                   if (file.exists()) {
                        file.delete();
                   }
                   getNotificationManager().cancel(1);
                   stopForeground(true);
                   Toast.makeText(DownloadService.this, "取消",Toast.LENGTH_SHORT).show();
                 }
            }
       }
}

private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
   }

   private Notification getNotification(String title, int progress) {
       Intent intent = new Intent(this, DownloadTestActivity.class);
       PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
       NotificationCompat.Builder mBuilder ;
       //如果targetSdkVersion >= 26,需要创建Channel
       if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel("default",
                   "defaultChannel", NotificationManager.IMPORTANCE_DEFAULT);
           //设置通知来时,是否亮起呼吸灯
           channel.enableLights(true);
           //设置呼吸灯颜色
           channel.setLightColor(Color.GREEN);
           //长按图标时是否显示通知内容
           channel.setShowBadge(true);
           //需要传入ChannelId
           mBuilder = new NotificationCompat.Builder(this, "default");
       } else {
           //targetSdkVersion < 26,不需要创建Channel
           mBuilder = new NotificationCompat.Builder(this);
       }
           mBuilder.setContentTitle(title) //设置通知标题
               .setContentIntent(pi) //设置通知内容
               .setWhen(System.currentTimeMillis()) //设置通知时间,这是获取了当前系统时间
               .setSmallIcon(R.drawable.android_white_18dp) //设置通知图标(系统状态栏上显示的小图标)
               .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                       R.drawable.android_white_24dp)) //设置通知图标(下拉系统状态栏时显示的图标)
               .setLights(Color.GREEN, 1000, 1000); //设置呼吸灯
       if (progress > 0) {
           mBuilder.setContentText(progress + "%");
           mBuilder.setProgress(100, progress, false);
       }
       return mBuilder.build();
   }
}


二、明天计划的事情

     实现分享功能


三、遇到的问题

   1. 通知逻辑有问题,下载过程中会不停地有声音提示,明天解决。

   2. 虽然完成了一个简单的下载功能,但是很多技术细节并不理解,需要再花时间去学习。


四、收获

      Service和Notification的基础知识



返回列表 返回列表
评论

    分享到