Android Service及多线程编程
Service的启动和解除
一.Service的两种启动方式
startService (没有通信的启动方式)
Intent startIntent = new Intent (this, MyService.class); //启动到你的Service类 startService(startIntent);
bindService (绑定活动可以通信的启动方式)
Intent bindIntent = new Intent(this, MyService.class); //参数BIND_AUTO_CREATE 表示活动和服务绑定后自动创建服务 isBind = bindService(bindIntent, connection, BIND_AUTO_CREATE);
二.Service的两种解除方式
stopService
Intent stopIntent = new Intent(this, MyService.class); stopService(stopIntent);
unbindService
if(isBind){ unbindService(connection); Log.i("Myservice", "服务解绑"); isBind = false; }else { Log.i("Myservice", "未注册服务服务"); }
这里解除服务如果单纯的使用
unbindService
会报Service not registered
的错。
定义Service类
继承Service
public class MyService extends Service{ ...... }
startService的操作
重写
onCreate()
,onStartCommand()
,onDestroy()
三个方法//创建服务时调用 public void onCreate() { super.onCreate(); } //启动服务时调用 public int onStartCommand(Intent intent, int flags, int startId) { ......//执行操作 return super.onStartCommand(intent, flags, startId); } //摧毁服务时调用 public void onDestroy() { super.onDestroy(); }
bindService的操作
在
MyService
中定义一个你要执行的类并继承Bander
,这里定义一个打印日志的类Logs
class Logs extends Binder{
public void log1(){
Log.i("Myservice", "The first log")
}
public void log2(){
Log.i("Myservice", "The second log");
}
}
实例化一个Logs
private Logs mBinder = new Logs();
在
onBind
方法中返回mBinder
public IBinder onBind(Intent intent) {
return mBinder;
}
在
MainActivity
中实例化一个Logs,并创建服务连接
private MyService.Logs logs;
private ServiceConnection connection = new ServiceConnection() {
//服务未连接时执行的操作
public void onServiceDisconnected(ComponentName name) {
}
//服务连接时要执行的操作
public void onServiceConnected(ComponentName name, IBinder service) {
logs = (MyService.Logs)service;
logs.startDowmload();
logs.getProgress();
}
};
三.清单文件配置<service>
<service android:name=".MyService"></service>
IntentService
可自行开启子线程和关闭服务
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService"); // 调用父类的有参构造函数
}
protected void onHandleIntent(Intent intent) {
...//子线程耗时操作
}
public void onDestroy() {
super.onDestroy();
}
}
四.使用前台服务
在MyService中的
onCreate
方法中添加通知,并用startForeground
创建前台服务
Notification.Builder builder = new Notification.Builder(getApplicationContext());
Intent mIntent = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mIntent, 0);
//设置通知的各项属性
builder.setTicker("通知来了!!");//设置通知第一次显示的文本
builder.setContentText("这是通知内容");
//通过使用PendingIntent设置点击事件
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(R.drawable.ic_launcher);//设置通知右下角的图标
//设置通知的图标
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
builder.setAutoCancel(true);
builder.setContentTitle("普通通知");
startForeground(1, builder.build());