1

我是新來的機器人。我想在本地設置通知,每天在特定時間觸發它。當我啓動服務...通知將立即觸發...如何使用Service和BroadcastReceiver在本地設置通知?

我想知道如何開火特定時間進行射擊立即

第1步通知:

public class startservice extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Button button=(Button) findViewById(R.id.button1); 
     button.setOnClickListener(new OnClickListener() { 
      public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(startservice.this,MainActivity.class); 
      startservice.this.startService(intent); 
     } 
    }); 

    } 

    } 

第2步:啓動服務

public class MainActivity extends Service { 

    AlarmManager am; 
    Calendar calendar; 
    int count=0; 


    @Override 
    public void onCreate() { 
     super.onCreate(); 

     am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
      calendar=Calendar.getInstance(); 
      setNotification(); 

    } 
    public void setNotification() { 
      Intent intent = new Intent(this, Startnotification.class); 
      calendar.set(Calendar.HOUR, 9); // At the hour you wanna fire 
      calendar.set(Calendar.MINUTE,12); // Particular minute 
      calendar.set(Calendar.SECOND, 0); 
      double x = Math.random(); 
      String value=String.valueOf(x); 
      intent.putExtra("name", value); 
      sendBroadcast(intent); 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(this, count,intent, PendingIntent.FLAG_UPDATE_CURRENT);  
      am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),3600000,pendingIntent); 
     count++; 
     } 
    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

} 

步驟3:廣播接收器

public class Startnotification extends BroadcastReceiver { 

    NotificationManager nm; 


    @SuppressWarnings("deprecation") 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     nm = (NotificationManager) context 
     .getSystemService(Context.NOTIFICATION_SERVICE); 
     String getvalue= intent.getStringExtra("name"); 
     CharSequence from = getvalue; 
     CharSequence message = "Android calendar..."; 
     PendingIntent contentIntent = PendingIntent.getService(context, 0, new Intent(),0); 

     Notification notif = new Notification(R.drawable.ic_launcher,"Android calendar...", System.currentTimeMillis()); 
     notif.setLatestEventInfo(context, from, message, contentIntent); 
     nm.notify(1, notif); 
     System.out.println("BroadcastReceiver"); 
    } 
    } 

如何實現它

在此先感謝...

回答

0

setNotification()您呼叫

 sendBroadcast(intent); 

這立即調用您Startnotification.onReceive()

此外,您設置小時的Calendar實例是這樣的:

calendar.set(Calendar.HOUR, 9); // At the hour you wanna fire 

可是你有沒有明確設置了12小時的時間AM/PM指示(HOUR用於設置12小時時間)。這意味着AM/PM指示燈仍將設置爲您撥打Calendar.getInstance()時的狀態。如果您運行此代碼,例如,在上午10:00,並將HOUR設置爲9,則由於時間過去,警報將立即停止。

相關問題