I hope anyone has any idea of this question because it has been driving me insane.
I have this service which I call IssueNotifier
, and it has some methods in it:
public void onCreate()
{
super.onCreate();
startService();
//initiate preferences to get values
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
choice = Integer.valueOf(prefs.getString("bgProcessPref", "15"));
delay = choice * minute;
if (VIEWISSUES_ACTIVITY != null)
Log.d(getClass().getSimpleName(), "ServiceTest started");
}
public void onDestroy()
{
super.onDestroy();
stopService();
if (VIEWISSUES_ACTIVITY != null)
Log.d(getClass().getSimpleName(), "ServiceTest stopped");
}
private void startService()
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable()
{
public void run()
{
if(VIEWISSUES_ACTIVITY.getNewIssues() > 0)
VIEWISSUES_ACTIVITY.sendNotification();
}
};
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
handler.post(runnable);
System.out.println(delay);
}
}, delay, delay);
}
private void stopService()
{
if(timer != null)
timer.cancel();
}
VIEWISSUES_ACTIVITY
is another Activity which will start this service, and it has its method sendNotification() which will notify the user if new messages has arrived:
//just pass the reference to the service
IssueNotifier.setMainActivity(this);
//start the service
startService(new Intent(this, IssueNotifier.class));
All this code works fine, but开发者_如何学C my problem is that I don't want VIEWISSUES_ACTIVITY to start this Service, but rather another Activity to do it, when I try to start the Service with another activity it doesn't work because sendNotification() is in the VIEWISSUES_ACTIVITY activity (it must be there). So how I can achieve my goal?
try :
Context.startService()
Implemented sendNotification()
(my own method) in the Service instead of Activity, this is the way to do it.
精彩评论