如果你希望服务可以一直保持运行状态,而不会由于系统的内存不足的原因导致被回收,就可以考虑使用前台服务, 前台服务与普通服务最大的区别在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果当然有时候你也可能不仅仅是为了防止服务被回收掉才使用前台服务的,比如墨迹天气,它的服务在后台更新天气数据的同时,还会在系统状态栏一直显示当前的天气信息
1.讲解服务首先当然就是创建一个服务类继承Service
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
0);
Notification notification = new Notification.Builder(this)
//设置图标
.setSmallIcon(R.drawable.ic_launcher)
//设置显示在状态栏的通知提示信息
.setAutoCancel(true)
//设置显示在状态栏的通知提示消息
.setTicker("有新新消息")
.setContentTitle("一条新通知")
.setContentText("恭喜您,加薪了")
.build();
//前台服务其实就是在Service类的OnCreate构建一个通知,
//只不过这里的通知使用startForeground()方法来启动
//没有使用NotifictionManager,startForeground表示运行在前台
startForeground(1, notification);
}
}
2.MainActivity:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button start_service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start_service=(Button) findViewById(R.id.start_service);
start_service.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent service=new Intent(MainActivity.this,MyService.class);
startService(service);
}
});
}
@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;
}
}