2017-02-11 86 views
1

我需要每隔30秒發出一次警報,我需要它在沒有運行應用程序的情況下被激活。但是,無論應用程序是否運行,AlarmReceiver都不會被調用。有什麼建議麼? 啓動方法是MainActivity.java類是否每隔30秒設置一次報警?

public void start() { 
    Calendar calendar=Calendar.getInstance(); 
    calendar.add(Calendar.SECOND, 30); 
    Intent intent = new Intent(MainActivity.this, AlarmReceiver.class); 
    PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 
    alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pintent); 
    Log.d("alarm","alarm set for alarm receiver"); 
} 

我的收款人提交

public class AlarmReceiver extends BroadcastReceiver { 
@Override 
public void onReceive(Context context, Intent intent) { 
    // Toast.makeText(context,"Alarm Receiver ",Toast.LENGTH_SHORT).show(); 
    Log.d("Alarm","Alarm receive"); 

} 

}

清單文件:

<?xml version="1.0" encoding="utf-8"?> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 

    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity" android:configChanges="keyboardHidden|orientation|screenSize"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <service android:name=".GetLocationService"/> 
    <receiver android:name=".AlarmReceiver" android:enabled="true"/> 
</application> 

在這裏,我能夠設置報警,但我沒有收到報警

+0

看看setExact – 2017-02-11 21:48:57

回答

0

在該頁面中有你所需要完成的例子:

https://www.thepolyglotdeveloper.com/2014/10/use-broadcast-receiver-background-services-android/

顯然你必須改線:

PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

PendingIntent pintent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

你的啓動方法改成這樣:

public void start() { 
    Intent alarmIntent = new Intent(this, AlarmReceiver.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0); 
    AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 
    int interval = 30 * 1000; // 30 seconds of interval. 
    manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent); 
    Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show(); 
} 

讓我知道,如果作品。

+0

得到這些警告信息無法啓動服務Intent {flg = 0x4 cmp = com.example.bipin.getlocationdetails/.AlarmReceiver(has extras)} U = 0:not found' –

+0

我編輯了我的答案,現在檢查。 – Diekrul

相關問題