2013-05-17 5 views
0

나는 실시간 점수를 확인하는 앱을 사용 중입니다. 가장 좋은 방법인지는 모르겠지만 Timertask, Service 및 Activity를 만들어 알림을 보냅니다.x 초마다 알림 전송

Timertask는 점수가 변경되면 매 x 초마다 확인하고 변경된 경우 서비스에 알립니다. 서비스에 알리면 사용자에게 알릴 활동을 호출합니다. 내 문제는 서비스에서 알림으로 활동을 호출하지 못했습니다. 여기

내가 점수 그러나 i 변수를 고려하지 않은, 예를 들어 내 코드 (입니다.

//import ... 

public class MyService extends Service{ 

    Notif notif = new Notif(); 

    private static final String TAG = "MyService"; 

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

    @Override 
    public void onCreate() { 
     Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onCreate"); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onStart"); 
     Timer time = new Timer(); // Instantiate Timer Object 
     final ScheduleTask st = new ScheduleTask(); // Instantiate SheduledTask class 
     time.schedule(st, 0, 5000); // Create Repetitively task for every 1 secs 
    } 

    @Override 
    public void onDestroy() { 
     Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show(); 
     Log.d(TAG, "onDestroy"); 
    } 

    public void checkI(int i){ 
     if (i==3){ 
      notif.initializeUIElements(); 
     } 
    } 
} 

TimerTask를

import ... 

// Create a class extends with TimerTask 
public class ScheduleTask extends TimerTask { 
    MyService myService = new MyService(); 
    Notif notif = new Notif(); 
    int i = 0; 
    // Add your task here 
    public void run() { 
     i++; 
     System.out.println("affichage numero " + i); 
     myService.checkI(i); 
    } 

    public int getI() { 
     return i; 
    } 
} 

import ... 

public class Notif extends Activity { 

    private static final int NOTIFY_ME_ID = 1987; 
    private NotificationManager mgr = null; 
    ScheduleTask scheduleTask = new ScheduleTask(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    } 

    void initializeUIElements() { 
     Notification note = new Notification(R.drawable.ic_launcher, 
       "Welcome to MyDoople.com", System.currentTimeMillis()); 
     PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(
       this, MainActivity.class), Notification.FLAG_ONGOING_EVENT); 

     note.setLatestEventInfo(this, "MyDoople.com", "An Android Portal for Development", 
       i); 
     // note.number = ++count; 
     note.flags |= Notification.FLAG_ONGOING_EVENT; 

     mgr.notify(NOTIFY_ME_ID, note); 
    } 
} 

답변

2

서비스 NOTIF 할 수있다 리소스가 필요한 경우 시스템에 의해 종료 될 수 있습니다. 귀하의 요구 사항에 맞게 AlarmManager을 마침표로 사용하는 것이 가장 좋습니다 캘리가 뭔가 해. 여기

더 참조입니다 : [1], [2]

+0

감사의 나는 이것에 대해 읽을거야 – user1965878

관련 문제