В фоновом режиме приложение отправляет запросы на сервер, в цикле. По задумке если ответ сервера содержит 1, надо отправить пуш уведомление. Код работает но оповещение нельзя закрыть и при переходе по уведомлению оно не пропадает.И еще, когда сервер выводит 1 , оповещения приходят до тех пор пока 1 не сменится 0, как можно это исправить?
public class MyService1 extends Service {
public MyService1() {
}
private final int NOTIFICATION_ID = 38;
private NotificationManager nn;
String q = "http://site/new.php";
public void onCreate(){
super.onCreate();
new JSON().execute(q);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public class JSON extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
while (true) {
onCreate();
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.contains("1")) {
Notification.Builder builder = new Notification.Builder(getApplicationContext());
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
builder
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_action_name)
.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(),R.drawable.ic_action_name))
.setTicker("new messsege")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle("Not")
.setContentText("put this mess");
Notification notification = builder.build();
notification.defaults = Notification.DEFAULT_VIBRATE;
startForeground(37,notification);
} else {
}
}
}
}