문제

I have a startApplicationService method in an activity. Therefore I have an alarm manager. startApplicationService method is calling background service. I want to use/call that method in onReceive method from my alarm manager. How to do it? Please help me. :)

EDITED: Added alarm manager class:

public class WatcherAlarm  extends BroadcastReceiver
{

    private final static String LOG_TAG = WatcherAlarm.class.getSimpleName();
    private AccessActivity activity = null;

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.d(LOG_TAG, "-------------------------- WATCHER ALARM ------ ON RECEIVE");
        if(activity != null) {
            activity.startApplicationService(intent.getExtras());
        }
    }

    public void startAlarm(AccessActivity activity, Bundle bundle)
    {
        this.activity = activity;
        AlarmManager alarmManager = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(activity, WatcherAlarm.class); // explicit
        i.putExtras(bundle);
        PendingIntent pi = PendingIntent.getBroadcast(activity, 0, i, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 20, pi); // Millisec * Second * Minute
    }

    public void stopAlarm(Context context)
    {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, WatcherAlarm.class); // explicit
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        alarmManager.cancel(pi);
    }
}

And here is the my startApplicationService method: It's starting AsyncTask.

public void startApplicationService(Bundle bundle)
{
    try {
        task = new ApplicationServiceTask(this);
        requestId = task.execute(bundle).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

I'm tried get activiy from context. But it's not possible. :(. Is there any way to say call startApplicationService method to activity from alarm manager?

Thank you for every advice.

Zeck

도움이 되었습니까?

해결책

No... because you have no guarantee that the Activity you are trying to call will even exist when your onReceive() is called.

What you can do is start that Activity using an Intent with an Extra indicating that the the caller is you BroadcastReceiver. The Activity can then check that Extra and call the method.

However, considering what you appear to want to do. I would recommend going with a Service. Since you are doing the work in the background anyways, I don't see a reason for wanting to do it in an Activity (unless, of course, you have a valid reason that does not show here).

See my answer here for an example of something similar.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top