2016-01-21 3 views
0

Я пытаюсь написать службу, которая работает в фоновом режиме и многократно вызывает веб-сервис, написанный на PHP. Этот веб-сервис возвращает мне JSON. Я получаю JSON, но не могу запустить уведомление.Фоновая служба в android, которая генерирует уведомления об изменении базы данных

Мой источник:

public class RepetedHttpCallService extends Service { 

    private static String TAG = RepetedHttpCallService.class.getSimpleName(); 
    private MyThread mythread; 
    public boolean isRunning = false; 
    NotifyServiceReceiver notifyServiceReceiver; 
    Notification noti; 

    HttpPost httppost; 
    HttpClient httpclient; 
    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Log.d(TAG, "onCreate"); 

     mythread = new MyThread(); 
    } 
    @Override 
    public synchronized void onDestroy() { 
     super.onDestroy(); 
     Log.d(TAG, "onDestroy"); 
     if(!isRunning){ 
      mythread.interrupt(); 
      mythread.stop(); 
     }  
    } 
    @Override 
    public synchronized void onStart(Intent intent, int startId) { 
     super.onStart(intent, startId); 
     Log.d(TAG, "onStart"); 
     if(!isRunning){ 
      mythread.start(); 
      isRunning = true; 
     } 
    } 

    class MyThread extends Thread{ 
     static final long DELAY = 5000; 
     @Override 
     public void run(){   
      while(isRunning){ 
       Log.d(TAG,"Running"); 
       try {     
        readWebPage(); 
        Thread.sleep(DELAY); 
       } catch (InterruptedException e) { 
        isRunning = false; 
        e.printStackTrace(); 
       } 
      } 
     } 

    } 

    public void readWebPage(){ 

     try { 
     httpclient = new DefaultHttpClient(); 
     httppost = new HttpPost("http://10.0.2.2:91/xxxxxxx/webServices/getValue.php"); 
     ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
     final String response = httpclient.execute(httppost,responseHandler); 
     if(!response.equals("")) 
     { 
      createNotification(); 
     } 
     Log.e("log_tag","POST URL response "+response.toString()); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    @SuppressLint("NewApi") 
    public void createNotification() { 
     int counter=0; 
     NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 


      System.out.println("in notification"); 
      Intent intent = new Intent(this, MainActivity.class); 
      // Intent intent1=new Intent(this,SendNotification.class); 
      PendingIntent pIntent = PendingIntent.getActivity(getBaseContext(), counter, intent, 0);//FLAG_CANCEL_CURRENT, 
                        //FLAG_ONE_SHOT, 
                        //FLAG_UPDATE_CURRENT 
      //PendingIntent pIntent1 = PendingIntent.getActivity(this, counter, intent1, 0); 
      counter++; 

      String c=String.valueOf(counter); 
      noti = new Notification.Builder(getApplicationContext()) 
       .setContentTitle("New mail from " + "[email protected]") 
       .setContentText("Sub "+counter) 
       .setContentIntent(pIntent) 
       .addAction(R.drawable.ic_launcher, "make", pIntent) 
       .setTicker("got notification "+counter) 
       .build(); 

      noti.flags = Notification.FLAG_AUTO_CANCEL; 


      notificationManager.notify(counter, noti); 

    } 
} 

Служба начинается и дает мне JSON каждые 5 секунд. Поскольку я называю это в отдельном потоке, я знаю, что я где-то здесь не так, как мне нужно передать контекст. Но я не уверен, как это сделать. Есть ли другой способ достичь этого?

+0

Немного не по теме, но почему вы неоднократно вызова веб-сервиса? это плохая практика. Вместо этого используйте push-уведомления GCM. –

ответ

0

Вам необходимо установить значок для уведомления. Вы можете установить его с помощью

.setSmallIcon() Обновленный фрагмент становится

noti = new Notification.Builder(getApplicationContext()) 
.setContentTitle("New mail from " + "[email protected]") 
.setContentText("Sub "+counter) 
.setContentIntent(pIntent) 
.addAction(R.drawable.ic_launcher, "make", pIntent) 
.setTicker("got notification "+counter) 
.setSmallIcon(R.drawable.ic_launcher) 
.build(); 
noti.flags = Notification.FLAG_AUTO_CANCEL;` 
+0

спасибо, что это сработало –