Android:闹钟无法启动服务

时间:2016-01-26 18:20:29

标签: android service android-service alarmmanager android-alarms

要求:重复启动后台服务

设计:使用AlarmManager

我做了什么:

<service
    android:name=".MyService"
    android:exported="false" >
</service>

AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), SERVICE_ALARM_INTERVAL, pendingIntent);

服务类是直截了当的extends Service,其中包含:

@Override
public void onCreate() {              
    HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    //Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
    mContext = getApplicationContext();
    Toast.makeText(mContext, "Service!!!!!", Toast.LENGTH_LONG).show();
    Log.e("tag", "Service!!!");
}

问题: Toast消息和Log打印未执行。

我在这里做错了什么?

谢谢,

2 个答案:

答案 0 :(得分:2)

您正在使用PendingIntent.getBroadcast() - 这会触发广播。如果要触发服务,则需要使用PendingIntent.getService()

答案 1 :(得分:1)

试试这个

<强>的AndroidManifest.xml

<receiver android:name=".AlarmReceiver">
   <intent-filter>
        <action android:name="com.example.project.AlarmReceiver" />
   </intent-filter>
</receiver>

<强> MainActivity.java

Intent intent = new Intent(context, AlarmReceiver.class);

intent.setAction("com.example.project.AlarmReceiver");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);

AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), SERVICE_ALARM_INTERVAL, pendingIntent);

<强> AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Alarm received!!!!!", Toast.LENGTH_LONG).show();
    }

}

将使用广播接收器调用AlarmManager,如上所示