2

我有以下广播接收器,当手机启动(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()而言,该服务在 using 调用时有效,但在PendingIntent.

4

2 回答 2

6

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

于 2012-05-30T03:46:31.453 回答
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);
    }
于 2012-05-30T03:57:01.800 回答