Issue
Im developing Android for a month now and can't seem to find a solution with this.
What I want is to send a notification if there's any change in the Database, can't seem to find the answer on Google. What I want to know is: should I run asynctask on service? Or directly run the code inside the doInBackground on startcommand on MyService class? How do I achieve this?
I tried putting asynctask on service and using the code on doInBackground, but can't make it work, so if you guys know the answer, can you post a little code to guide me up? Thanks
Solution
`public class AlertService extends Service { public AlertService() { }
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StringRequest sr = new StringRequest(Request.Method.POST, "http://localhost/ServiceAlarme.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try
{
JSONObject js=new JSONObject(response);
String etat=js.getString("etat");
if(etat.equals("1"))
{
int NOTIFICATION_ID = 12345;
NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification.Builder(getApplicationContext()).setContentTitle("SERVICE ALARME").setContentText("Alerte du ALARME du GAZ").setSmallIcon(R.mipmap.bubble).build();
n.defaults |= Notification.DEFAULT_SOUND;
n.flags |=Notification.FLAG_AUTO_CANCEL;
long[] vibrate = { 0, 100, 200, 300 };
n.vibrate = vibrate;
notif.notify(NOTIFICATION_ID,n);
}
else
{
}
}
catch(Exception e)
{
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("d","0");
return params;
}
};
RequestQueue rq= Volley.newRequestQueue(getApplicationContext());
rq.add(sr);
return super.onStartCommand(intent, flags, startId);
}
} `
Answered By - haythem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.