通过警报启动服务不起作用

时间:2012-05-30 03:43:12

标签: android service broadcastreceiver android-pendingintent repeatingalarm

我有以下广播接收器,当手机启动时调用(Bootreciever.java)并且我正在尝试使用重复警报启动间歇运行的服务。

public void onReceive(Context context, Intent intent) {

    Toast.makeText(context,"Inside onRecieve() :D" , Toast.LENGTH_LONG).show();
    Log.d(getClass().getName(), "Inside onRecieve() :D");


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


    Intent i = new Intent(context, MyService.class);

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);

    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 3000, 1000, pi);

}

基本上,我设置一个重复闹钟来触发3秒,之后每秒触发一次。收到启动完成广播就好 - 但服务没有启动。 MyService.java看起来像这样:

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(this, "Hello from MyService!", Toast.LENGTH_LONG);

        Log.d(getClass().getName(), "Hello from MyService!");

        stopSelf();

        return super.onStartCommand(intent, flags, startId);
    }

启动服务时我做错了什么?

Logcat没有告诉我任何事情,我在清单中定义了服务。使用startService()调用时,此服务本身可行,但在PendingIntent中使用时似乎失败。

2 个答案:

答案 0 :(得分:6)

而不是PendingIntent.getBroadcast()使用PendingIntent.getService()

答案 1 :(得分:1)

我认为你应该检查一下你的持续时间,因为android会因为频繁触发的警报而有点挑剔。为了启动服务,最好的方法是设置警报以将意图广播到广播接收器,然后让它启动您的服务。

示例1接收者:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class QoutesReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // log instruction
        Log.d("SomeService", "Receiving Broadcast, starting service");
        // start the qoute service

        Intent newService = new Intent(context, SomeService.class);
        context.startService(newService);
    }

}

示例2设置警报的功能(此示例每2分钟运行一次):

public void setAlarm(Context context) {


        // Get the current time
        Calendar currTime = Calendar.getInstance();

        // Get the intent (start the receiver) 
        Intent startReceiver = new Intent(context, MyReceiver.class);

        PendingIntent pendReceiver = PendingIntent.getBroadcast(context, 0,
                startReceiver, PendingIntent.FLAG_CANCEL_CURRENT);

        // call the Alarm service
        AlarmManager alarms = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        //Setup the alarm

        alarms.setRepeating(AlarmManager.RTC_WAKEUP,
                currTime.getTimeInMillis() + (2 * 60 * 1000), 2 * 60 * 1000,
                pendReceiver);
    }