Я пытаюсь выполнить метод {public void} в Service из запланированного TimerTask, который периодически выполняется.
Этот TimerTask периодически проверяет условие.Если это правда, он вызывает метод через {className}. {MethodName};
Однако, поскольку Java требует, метод должен быть {public public static}, если я хочу использовать {className} с {.точка}
Проблема заключается в том, что этот метод предназначен для уведомления с использованием Toast (всплывающее уведомление Android) и строки состояния. Чтобы использовать эти уведомления, необходимо использовать
Context context = getApplicationContext();
Но для этого нужнометод не должен иметь модификатор {static} и находится в классе Service.
Итак, в основном я хочу, чтобы фоновая служба оценила условие из запланированного TimerTask и выполнила метод в классе Service.
Может кто-нибудь помочь мне, каков правильный способ использования Service, вызывая метод, когда определенное условие удовлетворяется во время цикла оценки?
Вот собственно строки кода:
Класс TimerTask (WatchClipboard.java) :
public class WatchClipboard extends TimerTask {
//DECLARATION
private static GetDefinition getDefinition = new GetDefinition();
@Override
public void run() {
if (WordUp.clipboard.hasText()) {
WordUp.newCopied = WordUp.clipboard.getText().toString().trim().toLowerCase();
if (!(WordUp.currentCopied.equals(WordUp.newCopied))) {
WordUp.currentCopied = WordUp.newCopied; Log.v(WordUp.TAG, WordUp.currentCopied);
getDefinition.apiCall_Wordnik();
FetchService.instantNotification(); //it requires this method to have {static} modifier, if I want call in this way.
}
}
}
}
И класс Service (FetchService.java) : если я поменяюМодификатор e к статическому, возникают проблемы {Context}
public class FetchService extends Service {
public static final String TAG = "WordUp"; //for Logcat filtering
//DECLARATION
private static Timer runningTimer;
private static final boolean THIS_IS_DAEMON = true;
private static WatchClipboard watchClipboard;
private static final long DELAY = 0;
private static final long PERIOD = 100;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() { Log.v(WordUp.TAG, "FetchService.onCreate()");
super.onCreate();
//TESTING SERVICE RUNNING
watchClipboard = new WatchClipboard();
runningTimer = new Timer("runningTimer", THIS_IS_DAEMON);
runningTimer.schedule(watchClipboard, DELAY, PERIOD);
}
@Override
public void onDestroy() {
super.onDestroy();
runningTimer.cancel();
stopSelf(); Log.v(WordUp.TAG, "FetchService.onCreate().stopSelf()");
}
public void instantNotification() { //If I change the modifier to static, {Context} related problems occur
Context context = getApplicationContext(); // application Context
//use Toast notification: Need to accept user interaction, and change the duration of show
Toast toast = Toast.makeText(context, WordUp.newCopied+": "+WordUp.newDefinition, Toast.LENGTH_LONG);
toast.show();
//use Status notification: need to automatically expand to show lines of definitions
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.icon; // icon from resources
CharSequence tickerText = WordUp.newCopied; // ticker-text
long when = System.currentTimeMillis(); // notification time
CharSequence contentTitle = WordUp.newCopied; //expanded message title
CharSequence contentText = WordUp.newDefinition; //expanded message text
Intent notificationIntent = new Intent(this, WordUp.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(WordUp.WORDUP_STATUS, notification);
}
}