以下代码必须在设置时间(单击按钮)后 10000 毫秒后启动警报 .. 但是AlarmManager
单击按钮后立即启动服务为什么?包pit.opensource.notificationapp;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class NotificationAppActivity extends Activity {
private PendingIntent pendingIntent;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button)findViewById(R.id.btnset);
buttonStart.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
setAlarm();
//setAlarm(25);
}});
}
void setAlarm(){
Intent myIntent = new Intent(NotificationAppActivity.this, ShowNotification.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent = PendingIntent.getService(NotificationAppActivity.this, 445454, myIntent, 0);
//alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()-cal2.getTimeInMillis(), pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, 10000, pendingIntent);
}
}
显示通知服务
package pit.opensource.notificationapp;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class ShowNotification extends Service {
@Override
public void onCreate() {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "Alaaaaaaaaaarm ", Toast.LENGTH_LONG).show();
Log.d("Aalram","Alaaaaaaaaaarm");
}
}