我现在正在开发Android一个月,似乎无法找到解决方案。
我想发送的通知是,如果数据库中有任何更改,似乎无法在Google上找到答案。我想知道的是:我应该在服务上运行asynctask吗?还是直接在MyService类的startcommand的doInBackground内部运行代码?我该如何实现?
我尝试将asynctask投入服务并在doInBackground上使用代码,但无法使其正常工作,因此,如果你们知道答案,可以张贴一些代码来指导我吗?谢谢
答案 0 :(得分:0)
`公共类AlertService扩展服务{ 公共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);
}
} `