尝试{
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
3000,pendingIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
RingAlaram.class
public class RingAlarm extends Service {
public void onCreate() {
Toast.makeText(getApplicationContext(), "hi there", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
并持续我的清单
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.alarmmanagerexample.AlarmManagerExample"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".RingAlarm"
android:exported="false" />
</application>
答案 0 :(得分:3)
您应该使用getService
代替getActivity
并传递应用程序上下文(getApplicationContext
)而不是活动上下文(this
)。
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(getApplicationContext(), RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 3000, pendingIntent);
RingAlaram.class
public class RingAlarm extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "hi there", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
还将标志设置为PendingIntent.FLAG_UPDATE_CURRENT而不是CANCEL
将清单上的服务声明设置为<packagename>.RingAlarm
可能是com.example.alarmmanagerexample.RingAlarm
(我不了解您的项目结构)。
答案 1 :(得分:1)
将getActivity更改为getService
Intent intent = new Intent(this, RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getService(this,
12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
3000,pendingIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}