我正在关注设置警报管理器时发布的HERE代码,但我根本无法使用它。
此代码位于名为“Alarm”的类中:
package com.sjjgames.abortionapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5000, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
我已将此代码添加到清单中:
<receiver android:process=":remote" android:name="Alarm"></receiver>
<service android:enabled="true" android:name="com.sjjgames.abortionapp.YourService" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
这是一个名为“YourService”的类:
package com.sjjgames.abortionapp;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class YourService extends Service
{
Alarm alarm = new Alarm();
public void onCreate()
{
super.onCreate();
}
public void onStart(Context context,Intent intent, int startId)
{
alarm.SetAlarm(context);
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
我希望每隔5秒就会显示一次祝酒词。
答案 0 :(得分:0)
您的服务不会调用onStart()方法。您需要使用onStartCommand():
,而不是onStart()方法@Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarm.setAlarm(this);
return START_NOT_STICKY;
}
我建议你在类中的每个重写方法中添加@Override注释。因此,如果将@Override添加到onStart()方法,代码将无法编译,并且更容易发现错误。