Service

自定义Servive要在清单文件中注册

前台服务

展示在界面,可与用户交互的。

创建一个服务类:

public class MusicPlayerService extends Service {
  
  private static final String TAG = MusicPlayerService.class.getSimpleName();
  
  @Override
  public void onCreate() {
   super.onCreate();
  Log.d(TAG, "onCreate()");
  }
  
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand()");
  }
  
  @Override
  public IBinder onBind(Intent intent) {
   Log.d(TAG, "onBind()");
   // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
  }

在onStartCommand()方法中:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  Log.d(TAG, "onStartCommand()");
  // 在API11之后构建Notification的方式
  Notification.Builder builder = new Notification.Builder
    (this.getApplicationContext()); //获取一个Notification构造器
  Intent nfIntent = new Intent(this, MainActivity.class);
  
  builder.setContentIntent(PendingIntent.
    getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
    .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
      R.mipmap.ic_large)) // 设置下拉列表中的图标(大图标)
    .setContentTitle("下拉列表中的Title") // 设置下拉列表里的标题
    .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
    .setContentText("要显示的内容") // 设置上下文内容
    .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
  
  Notification notification = builder.build(); // 获取构建好的Notification
  notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
	// 参数一:唯一的通知标识;参数二:通知消息。
	startForeground(110, notification);// 开始前台服务

}

@Override
public void onDestroy() {
  Log.d(TAG, "onDestroy()");
  stopForeground(true);// 停止前台服务--参数:表示是否移除之前的通知
  super.onDestroy();
}

IntentService

线程和Service的结合。执行完自动关闭。
不用开启线程,但是要用广播传值.

public class MyService3 extends IntentService {

    public MyService3() {
        super("aaa");
    }
    public MyService3(String name) {
        super(name);
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand( Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        //耗时操作
        for (int i = 0; i < 10; i++) {
            Log.i("TAG", "onHandleIntent:  "+i+"--"+Thread.currentThread().getName());

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值