AlarmManager定时重复任务,发送心跳

package com.example.alarm_1;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, MyService.class);

		PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
				0);

		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		Log.i("Alarm", "Alarm");
		// am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5*1000,
		// pendingIntent);  ///单次不重复

		 am.setRepeating(AlarmManager.RTC_WAKEUP ,
		 System.currentTimeMillis(), 10*1000, pendingIntent);//TTTT   重复
//		am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
//				System.currentTimeMillis(), 10 * 1000, pendingIntent);TTTT  重复

	}
}
package com.example.alarm_1;

import java.util.Date;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * @author Administrator
 * 
 */
public class MyService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO 自动生成的方法存根
		return null;
	}

	@Override
	public void onCreate() {
		// TODO 自动生成的方法存根

	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO 自动生成的方法存根

		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		// player.stop();
		Log.i("--------------------暂停----------------------", "暂停");
		Toast.makeText(this, "暂停", Toast.LENGTH_SHORT).show();

	}

	@Override
	public void onDestroy() {
		// TODO 自动生成的方法存根

	}

}// / class MyService


    






    

    
        
            
                

                
            
        
                
        
    



效果是:每隔10s执行一次服务,延迟5s后显示“暂停”提示,循环发生。这个有大作用,这5s可以访问数据库,往里写数据,或者保持在线状态,

你可能感兴趣的:(Android)