android service
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = new Intent(); intent.setClass(TestActivity.this, FirstService.class); startService(intent);
package mars.service1; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; public class FirstService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub System.out.println("Service onBind"); return null; } //当创建一个Servcie对象之后,会首先调用这个函数 @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); System.out.println("Service onCreate"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(run).start(); // TODO Auto-generated method stub //System.out.println("flags--->" + flags); //System.out.println("startId--->" + startId); //System.out.println("Service onStartCommand"); return START_NOT_STICKY; } Runnable run=new Runnable(){ @Override public void run() { // TODO Auto-generated method stub int i=0; while(true){ i++; System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&"+i); if(i>10000000)break; } }}; @Override public void onDestroy() { // TODO Auto-generated method stubo System.out.println("Service onDestory"); super.onDestroy(); } }
<service android:name=".FirstService"></service>
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); PendingIntent pi = PendingIntent.getService(this, 0, new Intent(this, FirstService.class), Intent.FLAG_ACTIVITY_NEW_TASK); long now = System.currentTimeMillis(); am.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, 3000, pi);