您的位置:首页 > 编程语言

第一行代码 第10章 服务 -- 前台服务与IntentService

2017-07-23 13:35 357 查看
1、前台服务

与后台服务区别:它会一直有一个正在运行的图标在系统的状态栏显示,类似通知。

创建前台服务

在服务的onCreate()方法中添加一下代码:

Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("这是一个前台服务")
.setContentText("前台服务显示的内容")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);


通过调用startForeground()方法,将service变成一个前台服务,并在系统状态栏显示出来

startForeground()方法有两个参数

第一个参数是通知的id,标识符

第二个参数是Notification对象。

IntentService

前面我们创建的服务都是运行在主线程中,如果在服务中处理一些耗时的逻辑,就很容易出现ANR(Application Not Responding)的情况。

这个时候就需要我们在服务的每个具体的方法中开启一个子线程,然后在子线程中处理耗时逻辑。

类似如下情况:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand executed");
new Thread(new Runnable(){

@Override
public void run(){
// 处理逻辑

// 处理完成后,调用stopSelf(),自动停止服务
stopSelf();
}
}
).start();
return super.onStartCommand(intent, flags, startId);
}


为了避免在创建服务时忘记开启线程和调用stopSelf()方法,Android提供了IntentService类来处理。

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btnStart = (Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainActivity", "MainActivity thread id is : " + Thread.currentThread().getId());
Intent startIntent = new Intent(MainActivity.this, MyIntentService.class);
startService(startIntent);
}
});
}
}


创建IntentService

public class MyIntentService extends IntentService {

public MyIntentService() {
super("MyIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService", "MyIntentService thread id is : " + Thread.currentThread().getId());
}

@Override
public void onDestroy() {
Log.d("MyIntentService", "onDestroy executed");
super.onDestroy();
}
}


提供的是一个无参的构造函数,并且必须在其内部调用父类的有参构造函数。

onHandleIntent()方法就在子线程中运行的,可以在这里处理耗时的逻辑。当逻辑处理完后,服务会自动停止。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: