android学习十八(Service服务的基本用法)
发表时间:2020-10-19
发布人:葵宇科技
浏览次数:38
定义一个办事
在项目中定义一个办事,新建一个ServiceTest项目,然后在这个项目中新增一个名为MyService的类,并让它持续自Service,完成后的代码如下所示:
package com.jack.servicetest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
今朝MyService中只用一个onBind()办法,这个办法是Service中独一的一个抽象办法,所以必须要在子类诚实现。既然定义了一个办事,天然应当在办事中去处理一些工作,那边那边理工作的逻辑应当写在哪里?这时我们就可以重写Service中的别的一些办法了,如下所示:
package com.jack.servicetest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
}
可以看到,这里我们又重写了onCreate(),onDestroy()和onStartCommand(Intent intent, int flags, int startId)这三个办法,它们是每个办事中最常用到的三个办法。个中onCreate办法会在办事创建的时刻调用,onStartCommand办法会在每次办事启动的时刻调用。onDestroy()办法会在办事烧毁的时刻调用。
平日情况下,如不雅我们欲望办事一旦启动就急速去履行某个动作,就可以将逻辑写在onStartCommand办法里。而当办事烧毁时,我们又应当在onDestroy()办法中去收受接收那些不在应用的资本。
别的须要留意的是,没一个办事都须要在AndroidManifest.xml文件中进行注册才能生效,android四大年夜组件都须要进行注册。于是我们修改AndroidManifest.xml文件,代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jack.servicetest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.jack.servicetest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.jack.servicetest.MyService"></service>
</application>
</manifest>
如许的话,就已经将一个办事定义好了。
启动和停止办事
定义好了办过后,接下来就应当推敲若何启动以及停止这个办事。启动办事和停止办事重要借助Intent来实现,下面我们在ServiceTest项目中测验测验去启动已经停止MyService这个办事。
起首修改activity_main.xml中的代码,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start service"
/>
<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stop service"
/>
</LinearLayout>
膳绫擎的构造重要参加了2个按钮,用来启动和停止办事。
然后修改MainActivity中的代码,如下所示:
package com.jack.servicetest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button startService;
private Button stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button) findViewById(R.id.start_service);
stopService=(Button) findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.start_service:
Intent startIntent =new Intent(this,MyService.class);
startService(startIntent);//启动办事
break;
case R.id.stop_service:
Intent stopIntent =new Intent(this,MyService.class);
stopService(stopIntent);//停止办事
break;
default:
break;
}
}
}
膳绫擎我们在onCreate办法平分别获取到start service按钮和stop service按钮的实例,并给它们注册了点击
事宜。然后在start service按钮的点击事沂攀琅绫擎,我们构建出了一个Intent对象,并调用startService()
办法来启动MyService这个办事。在stop service按钮的点击事沂攀里,我们同样构建出了一个Intent对象,并调用
stopService()办法来停止MyService这个办事。startService()和stopService()办法都是定义在Context
类中的,所以我们在晃荡里可以直接调用这两个办法。留意,这琅绫抢满是由晃荡来决定办事何时停止的,如不雅没有点击stop service
按钮,办事就会一向处于运行状况。那办事有什么办法让本身停下来了?只须要在MyService的任何一个地位调用shopSelf()
办法就能让办事停止下来了。
接下来我们要推敲,若何才能证实办事已经成功启动或者停止了?最简单的办法就是在MyService的几个办法中参加打印日记,如下所示:
package com.jack.servicetest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("MyService", "onCreate()");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("MyService", "onDestroy()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("MyService", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
}
如今运行法度榜样,进行测试,法度榜样的主界面如下所示:
[img]http://img.blog.csdn.net/20141120211442358?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
点击一下start service按钮,不雅察logcat打印的日记如下所示:
[img]http://img.blog.csdn.net/20141120211554945?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
MyService中的onCreate办法和onStartCommand办法都履行了,解释办事已经成功启动了,并且可以在正在运行的办事列表中找到。
在点击下stop service,不雅察logcat日记的输出:
[img]http://img.blog.csdn.net/20141120211833644?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
由此证实MyService办事确切已经成功停止下来了。
onCreate办法和onStartCommand办法的差别:onCreate办法是在办事第一次创建的时刻调用的,而onStartCommand方轨则在每次启动办事的时刻都邑调用,因为刚才我们是第一次点击start service按钮,办事此时还未创建过,所以两个办法都邑履行,之后如不雅你在持续多点击几回start service按钮,你就会发明只有onStartCommand办法可以获得履行了。
晃荡和办事进行通信
今朝我们欲望在MyService里供给一个下载的功能,然后再晃荡中可以决定何时开端下载,以及随时查看下载进。实现这个功能的思路是创建一个专门的Binder对象来对下载功能进行治理,修改MyService中的代码:如下所示:
package com.jack.servicetest;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private DownloadBinder mBinder=new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService", "startdownload executed");
}
public int getProgress(){
Log.d("MyService", "getProgress executed");
return 0;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("MyService", "onCreate()");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("MyService", "onDestroy()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("MyService", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
}
这里我们新建了一个DownloadBinder类,并让它持续自Binder,然后再它的内部供给开端下载以及查看下载进度的办法。当然这只是两个模仿的办法,并没有实现真正的功能,我们在这两个办法平分别打印了一行日记。
接着,在MyService中创建了DownloadBinder的实例,然后再onBind()办法里返回了这个实例,如许MyService中的工作就全部完成了。
下面我们须要在晃荡中调用办事里的办法,起首须要在构造文件中新曾两个按钮,修改activity_main.xml中的代码,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start service"
/>
<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stop service"
/>
<Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bind service"
/>
<Button
android:id="@+id/unbind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="unbind service"
/>
</LinearLayout>
这两个晃荡用于在晃荡中进行绑定和撤消绑定办事,当一个晃荡和办事绑定了之后,就可声调用该办事里的Binder供给的办法了,修改MainActivity中的代码,如下所示:
package com.jack.servicetest;
import com.jack.servicetest.MyService.DownloadBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection=new ServiceConnection() {
/*
* 这里创建了一个ServiceConnection的匿名类,在这里重写了onServiceConnected办法和
* onServiceDisconnected办法,这两个办法分别会在晃荡与办事成功绑定以及解除绑定的时刻调用。
* 在onServiceConnected办法中,我们又经由过程向下转型获得了DownloadBinder的实例,有了这个
* 实例,晃荡和办事之间的关系就变得异常慎密了,如今我们可以在晃荡中根据具体的场景来调用DownloadBinder
* 中的任何public办法,及实现了批示办事干什么,办事就干什么的功能,这里只做了简单的测试,在onServiceConnected
* 中调用了DownloadBinder的startDownload(),getProgress()办法。
* */
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
downloadBinder=(MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button) findViewById(R.id.start_service);
stopService=(Button) findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.start_service:
Intent startIntent =new Intent(this,MyService.class);
startService(startIntent);//启动办事
break;
case R.id.stop_service:
Intent stopIntent =new Intent(this,MyService.class);
stopService(stopIntent);//停止办事
break;
case R.id.bind_service:
/*
*如今我们须要进行晃荡和办事的绑定,构建一个Intent对象,然后调用bindService()办法将
*MainActivity()和MyService进行绑定。 bindService办法接收留个参数,第一个参数就是
*膳绫擎创建出的Intent对象,第二个参数就是前面创建出的ServiceConnection的实例,第三个
*参数则是一个标记位,这里传入BIND_AUTO_CREATE表示在晃荡和办事进行绑定后主动创建办事。
*这会使得MyService中的onCreate()办法获得履行,但onStartCommand()办法不会履行。
* */
Intent bindIntent=new Intent(this,MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);//绑定办事
break;
case R.id.unbind_service:
/*
* 如不雅我们想解除晃荡和办事之间的绑定,调用一下unbindService()办法就可以了。
* */
unbindService(connection);//解绑办事
break;
default:
break;
}
}
}
大年夜新运行下法度榜样,界面如下所示:
[img]http://img.blog.csdn.net/20150105162929487?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
点击以下bind service,然后可以不雅察logcat中打印的日记如下图所示:
[img]http://img.blog.csdn.net/20150105163058187?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
可以看到,起首是MyService的onCreate()办法获得了履行,然后startDownload和getProgeress办法获得了履行,解释我们确切已经在晃荡力成功的调用了办事里供给的办法了。别的须要留意的,任何一个办事在全部应用法度榜样范围内都是通用的,即MyService不仅可以和MainActivity绑定,还可以和任何一个其他的晃荡进行绑定,并且在绑定完成之后他们都可以获取到雷同的DownloadBinder实例。
办事的生命周期
办事也有本身的生命周期,前面我们应用到的onCreate(),onStartCommand(),onBind()和onDestroy()等办法
都是在办事的生命周期内可能回掉落的办法。
一旦在项目标任何地位调用了Context的startService()办法,响应的办事就会启动起来,并回调onStartCommand()。如不雅 这个办事之前还没创建过,onCreate()办法会先于onStartCommand()办法履行。办事启动了之后一向保持运行状况,
直到stopService()或stopSelf()办法被调用。留意固然每调用一次startService()办法,onStartCommand()就会
履行一次,但实际膳绫强个办事都只会存在一个实例。所以不管你调用了若干次startService()办法,只需调用一次stopService()或stopSelf()办法,办事就会停止下来了。
别的,还可声调用Context的bindService()来获取一个办事的持久连接,这时就会回调办事中的onBind()办法。类似地,如不雅这个办事之前还没有创建过,onCreate()办法会先于onBind()办法履行。之后,调用方可以获取到onBind()办法里返回的IBinder对象的实例,如许就能自由地和办事进行通信了。只要调用方和办事之间的连接没有断开,办事就会一向保持运行状况。
当调用了startService()办法后,又去调用stopService()办法,这时办事中的onDestroy()办法就会履行,表示
办事已经烧毁了。类似地,当调用了bindService()办法后,又去调用unbindService()办法,onDestroy()办法也会履行,这
两种情况都很好懂得。然则须要留意,我们是完全有可能对一个办事既调用了startService()办法,又调用了bindService()办法的,这种情况下该若何才能让办事烧毁掉落?根据android体系的机制,一个办事只要被启动或者绑定了之后就会一向处于运行状况,必须要让以上两种前提同时不知足,办事才能被烧毁。所以,这种情况下须要同时调用stopService()和unbindService()办法,onDestroy()办法才会履行。
应用前台办事
办事几乎都是在后台运行的,一向以来它都是默默的做着辛苦的工作。然则办事的体系优先级照样比较低的,当体系出现内存不足的情况时,就有可能会收受接收掉履┞俘在后台运行的办事。如不雅你欲望办事可以一向 保持运行状况,而 不会因为体系内存不足的原因导致被收受接收,就可以推敲应用前台办事。前台办事和通俗办事最大年夜的差别就在于,它会一向有一个正在运行的体系状况栏显示,下拉状况栏后可以看到加倍具体的信息,异常类似于通知的效不雅。
下面我们创建一个前台办事吧,修改MyService中的代码,如下所示:
package com.jack.servicetest;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private DownloadBinder mBinder=new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService", "startdownload executed");
}
public int getProgress(){
Log.d("MyService", "getProgress executed");
return 0;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
@SuppressWarnings("deprecation")
Notification notification=new Notification(R.drawable.ic_launcher,
"Notification comes",System.currentTimeMillis());
Intent notificationIntent=new Intent(this,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,notificationIntent,
0);
notification.setLatestEventInfo(this, "this is title", "this is content",
pendingIntent);
startForeground(1, notification);
/*
可以看到,这里只是修改了onCreate()办法中的代码,信赖这部分代码你会异常眼熟。这就是我们前面进修的
创建通知的办法。只不过此次在构建出Notification对象并没有应用NotificationManager来精晓知显示
出来,而是调用了startForeground()办法。这个办法接收两个参数,第一个参数是通知的id,类似于notify()办法
的第一个参数,第二个参数则是构建出来的Notification对象。调用startForeground()办法后就会让MyService变成
一个前台办事,并在体系状况显示出来。
*/
Log.d("MyService", "onCreate()");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("MyService", "onDestroy()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("MyService", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
}
如今从新运行下法度榜样,并点击start service或bind service按钮,MyService就会以前台办事的模式开启了,并且在体系状况栏会显示一个通知搁笔,下拉状况栏后可以看到该通知的具体内容,如下所示:
[img]http://img.blog.csdn.net/20150105172643085?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
应用IntentService
我们知道办事中的代码都是默认运行在主线程傍边,如不雅直接在办事里去处理一些耗时的逻辑,就很轻易出现ANR(Application Not Responding)的情况。
所以这个时刻,就须要用到Android多线程编程的技巧了,我们应当在办事的每个具体的办法里开启一个子线程,然后再这里去处理那些耗时的逻辑。是以,一个比较标准的办事就可以写成如下情势了:
package com.jack.servicetest;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
/*private DownloadBinder mBinder=new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService", "startdownload executed");
}
public int getProgress(){
Log.d("MyService", "getProgress executed");
return 0;
}
}*/
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//return mBinder;
return null;
}
/*@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
@SuppressWarnings("deprecation")
Notification notification=new Notification(R.drawable.ic_launcher,
"Notification comes",System.currentTimeMillis());
Intent notificationIntent=new Intent(this,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,notificationIntent,
0);
notification.setLatestEventInfo(this, "this is title", "this is content",
pendingIntent);
startForeground(1, notification);
可以看到,这里只是修改了onCreate()办法中的代码,信赖这部分代码你会异常眼熟。这就是我们前面进修的
创建通知的办法。只不过此次在构建出Notification对象并没有应用NotificationManager来精晓知显示
出来,而是调用了startForeground()办法。这个办法接收两个参数,第一个参数是通知的id,类似于notify()办法
的第一个参数,第二个参数则是构建出来的Notification对象。调用startForeground()办法后就会让MyService变成
一个前台办事,并在体系状况显示出来。
Log.d("MyService", "onCreate()");
}
*/
/*@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("MyService", "onDestroy()");
}*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("MyService", "onStartCommand");
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
//处理具体的逻辑
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
}
然则,这种办事一旦启动之后,就会一向处于运行状况,必须调用stopService()或者stopSelf()办法才能让办事停止下来。所以,如不雅想要实现一个办事履行完毕后主动停止的功能,就可以如许写:
package com.jack.servicetest;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
/*private DownloadBinder mBinder=new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService", "startdownload executed");
}
public int getProgress(){
Log.d("MyService", "getProgress executed");
return 0;
}
}*/
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//return mBinder;
return null;
}
/*@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
@SuppressWarnings("deprecation")
Notification notification=new Notification(R.drawable.ic_launcher,
"Notification comes",System.currentTimeMillis());
Intent notificationIntent=new Intent(this,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,notificationIntent,
0);
notification.setLatestEventInfo(this, "this is title", "this is content",
pendingIntent);
startForeground(1, notification);
可以看到,这里只是修改了onCreate()办法中的代码,信赖这部分代码你会异常眼熟。这就是我们前面进修的
创建通知的办法。只不过此次在构建出Notification对象并没有应用NotificationManager来精晓知显示
出来,而是调用了startForeground()办法。这个办法接收两个参数,第一个参数是通知的id,类似于notify()办法
的第一个参数,第二个参数则是构建出来的Notification对象。调用startForeground()办法后就会让MyService变成
一个前台办事,并在体系状况显示出来。
Log.d("MyService", "onCreate()");
}
*/
/*@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("MyService", "onDestroy()");
}*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("MyService", "onStartCommand");
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
//处理具体的逻辑
stopSelf();
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
}
固然这种写法并不复杂,然则总会有一些人忘记开启线程,或者忘记调用stopSelf()办法。为了可以简单地创建一个异步的,会主动停止的办事,android专门供给了一个IntentService类,这个类就很好的解决了前面所提到的两种难堪,下面我们来看下它的用法。
新建一个MyIntentService类持续IntentService,代码如下所示:
package com.jack.servicetest;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyIntentService extends IntentService {
/*
这里起首是供给了一个无参的构造函数,并且必须在其内部调用父类的有参构造函数。然后要在子类中去实现
onHandleIntent()这个抽象办法,在这个办法中可以处理一些具体的逻辑,并且不消担心ANR的问题,因为
这个办法已经是在子线程中运行的了。这里为了证实一下,我们在onHandleIntent()办法中打印了当前哨程的id。
别的根据IntentService的特点,这个办事在运行停止后应当是会主动停止的,所以我们又重写了onDestroy()办法,在
这里也打印l一行日记,以证实是不是停止掉落了。
*/
public MyIntentService() {
super("MyIntentService");//调用父类的有参构造函数
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
//打印当前哨程的id
Log.d("MyIntentService", "Thread id is "+Thread.currentThread().getId());
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d("MyIntentService", "onDestroy() executed");
}
}
接下来修改activity_main.xml中的代码,参加一个用于启动MyIntentService这个办事的按钮,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start service"
/>
<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stop service"
/>
<Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bind service"
/>
<Button
android:id="@+id/unbind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="unbind service"
/>
<Button
android:id="@+id/start_intent_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start intentservice"
/>
</LinearLayout>
然后修改MainActivity中的代码,如下所示:
package com.jack.servicetest;
//import com.jack.servicetest.MyService.DownloadBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private Button startIntentService;
//private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection=new ServiceConnection() {
/*
* 这里创建了一个ServiceConnection的匿名类,在这里重写了onServiceConnected办法和
* onServiceDisconnected办法,这两个办法分别会在晃荡与办事成功绑定以及解除绑定的时刻调用。
* 在onServiceConnected办法中,我们又经由过程向下转型获得了DownloadBinder的实例,有了这个
* 实例,晃荡和办事之间的关系就变得异常慎密了,如今我们可以在晃荡中根据具体的场景来调用DownloadBinder
* 中的任何public办法,及实现了批示办事干什么,办事就干什么的功能,这里只做了简单的测试,在onServiceConnected
* 中调用了DownloadBinder的startDownload(),getProgress()办法。
* */
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
/*downloadBinder=(MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();*/
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button) findViewById(R.id.start_service);
stopService=(Button) findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
startIntentService=(Button) findViewById(R.id.start_intent_service);
startIntentService.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.start_service:
Intent startIntent =new Intent(this,MyService.class);
startService(startIntent);//启动办事
break;
case R.id.stop_service:
Intent stopIntent =new Intent(this,MyService.class);
stopService(stopIntent);//停止办事
break;
case R.id.bind_service:
/*
*如今我们须要进行晃荡和办事的绑定,构建一个Intent对象,然后调用bindService()办法将
*MainActivity()和MyService进行绑定。 bindService办法接收留个参数,第一个参数就是
*膳绫擎创建出的Intent对象,第二个参数就是前面创建出的ServiceConnection的实例,第三个
*参数则是一个标记位,这里传入BIND_AUTO_CREATE表示在晃荡和办事进行绑定后主动创建办事。
*这会使得MyService中的onCreate()办法获得履行,但onStartCommand()办法不会履行。
* */
Intent bindIntent=new Intent(this,MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);//绑定办事
break;
case R.id.unbind_service:
/*
* 如不雅我们想解除晃荡和办事之间的绑定,调用一下unbindService()办法就可以了。
* */
unbindService(connection);//解绑办事
break;
case R.id.start_intent_service:
//打印主线程的id
Log.d("MainActivity", "Thread id is"+Thread.currentThread().getId());
Intent intentService=new Intent(this,MyIntentService.class);
startService(intentService);
break;
default:
break;
}
}
}
/*
办事也有本身的生命周期,前面我们应用到的onCreate(),onStartCommand(),onBind()和onDestroy()等办法
都是在办事的生命周期内可能回掉落的办法。
一旦在项目标任何地位调用了Context的startService()办法,响应的办事就会启动起来,并回调onStartCommand()。如不雅
这个办事之前还没创建过,onCreate()办法会先于onStartCommand()办法履行。办事启动了之后一向保持运行状况,
直到stopService()或stopSelf()办法被调用。留意固然每调用一次startService()办法,onStartCommand()就会
履行一次,但实际膳绫强个办事都只会存在一个实例。所以不管你调用了若干次startService()办法,只需调用一次stopService()
或stopSelf()办法,办事就会停止下来了。
别的,还可声调用Context的bindService()来获取一个办事的持久连接,这时就会回调办事中的onBind()办法。类似地,
如不雅这个办事之前还没有创建过,onCreate()办法会先于onBind()办法履行。之后,调用方可以获取到onBind()办法里
返回的IBinder对象的实例,如许就能自由地和办事进行通信了。只要调用方和办事之间的连接没有断开,办事就会一向保持运行状况。
当调用了startService()办法后,又去调用stopService()办法,这时办事中的onDestroy()办法就会履行,表示
办事已经烧毁了。类似地,当调用了bindService()办法后,又去调用unbindService()办法,onDestroy()办法也会履行,这
两种情况都很好懂得。然则须要留意,我们是完全有可能对一个办事既调用了startService()办法,又调用了bindService()办法的,
这种情况下该若何才能让办事烧毁掉落?根据android体系的机制,一个办事只要被启动或者绑定了之后就会一向处于运行状况,必须要让以上两种前提同时
不知足,办事才能被烧毁。所以,这种情况下须要同时调用stopService()和unbindService()办法,onDestroy()办法才会履行。
*/
可以看到,我们在start intentservice按钮的点击事沂攀琅绫擎去启动MyIntentService这个办事,并在这里打印了一下主线程的id,其实IntentService的用法和通俗的办事没什么两样。
在AndroidManifest.xml里注册,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jack.servicetest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.jack.servicetest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.jack.servicetest.MyService"></service>
<service android:name="com.jack.servicetest.MyIntentService"></service>
</application>
</manifest>
从新运行法度榜样,界面如下所示:
[img]http://img.blog.csdn.net/20150105182349250?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
点击start intentservice按钮后,不雅察LogCat中打印的日记,如下所示:
[img]http://img.blog.csdn.net/20150105182540578?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
可以看到MyIntentService和MainActivity地点的线程id不一样,并且onDestory()办法也获得了履行,解释MyIntentService在运行完毕后确切主动停止了。集开启线程和主动停止于一身。
办事的最佳实践---------后台履行的准时义务
Android中实现准时义务一般有两种方法,一种是应用java api里供给的Timer类,一种是应用android的Alarm机制。
这两种方法在多半情况下都能实现类似的效不雅,然则Timer有一个明显的短板,它并不太实用于那些须要经久在后台运行的准时义务。我们都知道,为了能让电池加倍耐用,每种手机都邑有本身的休眠策略,andorid手机就会在长时光不操作的情况下主动让cpu进入的到睡眠状况,这就有可能导致Timer中的准时义务无法正常运行。而Alarm机制不存在这种情况,它具有唤醒cpu的功能,即可以包管每次须要履行准时义务的时刻cpu都能正常工作。须要留意,这里的唤醒cpu和唤醒屏幕完全不是同一个概念,不要弄混淆了。
我们来看看Alarm机制的用法吧,重要须要借助AlarmManager类来实现。这个类和NotificationManager有点类似,都是经由过程调用Context的getSystemService()办法来获取实例的,只是这里须要传入的参数是Context.ALARM_SERVICE.
是以,获取一个AlarmManager的实例就可以写成:
AlarmManager manager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
接下来调用AarmManager的set()办法就可以设置一个准时义务了,比如说想要设定一个义务在10秒后履行,就可以写成:
long triggerAtTime=SystemClock.elapsedRealtime()+10*1000;
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);
第一个参数是一个整形参数,用于指定AlarmManager的工作类型,有四种值可选,分别是ELAPSED_REALTIME,ELAPSED_REALTIME_WAKEUP,
RTC 和 RTC_WAKEUP。个中ELAPSED_REALTIME表示让准时义务的触发大年夜体系开机开端算起,但不会唤醒cpu。
ELAPSED_REALTIME_WAKEUP同样表示让准时义务的触发时光大年夜体系开机开端算起,但会唤醒cpu。
RTC表示让准时义务的触发时光大年夜1970年1月1日0点开端算起,但不会唤醒cpu。
RTC_WAKEUP同样表示让准时义务的触发时光大年夜1970年1月1日0点开端算起,但会唤醒cpu。应用SystemClock.elapsedRealtime()办法
可以获取到体系开机至今所历经的毫秒数,应用System.currentTimeMillis()办法可以获取到1970年1月1日0点
至今所经历时光的毫秒数。
第二个参数就是准时义务触发的时光,以毫秒为单位。如不雅第一个参数应用的是ELAPSED_REALTIME或ELAPSED_REALTIME_WAKEUP则这里传入开机至今的时光在加上延迟履行的时光。如不雅第一个参数应用的是RTC或RTC_WAKEUP,则这里传入1970年1月1日0点至今的时光再加上延迟履行的时光。
第三个参数是一个PendingIntent,对于它应当不会陌生了 吧。这里我们一般会调用getBroadcast()办法来
获取一个可以或许履行广播的PendingIntent。如许当准时义务被触发的时刻,广播接收器的onReceive()办法就可以获得履行。
懂得了 set()办法的每个参数之后,你应当能想到,设定一个义务在10秒后履行还可以写成:
long triggerAtTime=System.curentTimeMillis()+10*1000;
manager.set(AlarmManager.RTC_WAKEUP,triggerAtTime,pendingIntent);
如今已经控制了Alarm机制的根本用法,下面我们就来创建一个可以经久在后台履行准时义务的办事。创建一个ServiceBestPractice项目,
然后新增一个LongRunningService类,代码如下所示:
package com.jcak.servicebestpractice;
import java.util.Date;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
public class LongRunningService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Log.d("LongRunningService","executed at "+new Date().toString());
}
}).start();
AlarmManager manager=(AlarmManager) getSystemService(ALARM_SERVICE);
int anHour=10*1000;
long triggerAtTime=SystemClock.elapsedRealtime()+anHour;
Intent i=new Intent(this,AlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(this, 0, i, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerAtTime, pi);
return super.onStartCommand(intent, flags, startId);
}
}
在onStartCommand()办法中开启了一个子线程,然后在子线程里就可以履行具体的逻辑操作了,这里简单的,只是打印了当前的时光。
创建线程之后的代码就是膳绫擎讲解的Alarm机制的用法,先是获取到了AlarmManager的实例,然后定义义务的触发时光为10秒,在应用PendingIntent指定处理准时义务的广播接收器为AlarmReceiver,最后调用set()办法完成设定。显然,AlarmReceiver不存在,我们就创建一个,代码如下所示:
package com.jcak.servicebestpractice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent i=new Intent(context,LongRunningService.class);
context.startService(i);
}
}
onReceiver()办法里的代码异常简单,就是构建出了一个Intent对象,然后去启动LongRunningService这个办事
。这就已经将一个经久办事在后台准时运行的办事完成了。因为一旦启动了LongRunningService,就会在onStartCommand()办法里设定一个准时义务,如许10秒后AlarmReceiver的onReceive()办法就将获得履行了,然后我们在这里再次启动LongRunningService,如许就形成了一个永远的轮回,包管LongRunningService可以每隔10秒就会启动一次,这个经久在后台运行的办事就完成了。
接下来,我们须要在打开法度榜样的时刻启动一次LongRunningService,之后LongRunningService就可以一向运行了。修改MainActivity中的代码,如下所示:
package com.jcak.servicebestpractice;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent(this,LongRunningService.class);
startService(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
最后要注册办事和广播,代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jcak.servicebestpractice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.jcak.servicebestpractice.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.jcak.servicebestpractice.LongRunningService"></service>
<receiver android:name="com.jcak.servicebestpractice.AlarmReceiver"></receiver>
</application>
</manifest>
如今运行一下法度榜样,然后不雅察LogCat中打印的日记,如图所示:
[img]http://img.blog.csdn.net/20150105220927069?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
可以看到LongRunningService每隔10秒打印一条日记。
别的须要留意的是,大年夜android4.4版开端,Alarm义务的触发时光将会变得不精确,有可能会延迟一段时光后义务才能获得履行。这并不是bug,而是体系在耗电方面进行的优化。体系会主动检测今朝有若干Alarm义务存在,然后将触发时光将近的几个义务存放在一路履行,这就可以大年夜幅度削减cpu被唤醒的次数,大年夜而有效延长电池的应用时光。
当然,如不雅请求Alarm义务的履行时光必须精确无误,android仍然供给l解决筹划。应用AlarmManager的setExact()办法来替代set()办法,就可以包管义务准时履行了。
http://blog.csdn.net/j903829182/article/details/41320241








