我需要检查来自Mysql的数据并在数据更新时显示警报(通知)。现在通知仅在应用程序打开但工具关闭时才起作用,它不起作用。如何解决这个问题,你能帮帮我吗?
我的代码(Service.java)
public class Myservice2 extends Service {
private Thread thread;
private boolean finish = false;
RequestQueue requestQueue;
String showUrl = "http://test/readData.php";
private static final String TAG = "ServiceDemo";
final static String MY_ACTION = "MY_ACTION";
private final long UPDATE_INTERVAL = 5000;
private final IBinder mBinder = new MyBinder();
String weightString ;
private Timer timer= new Timer();
private int g=0;
@Override
public void onCreate() {
pollForUpdates();
requestQueue = Volley.newRequestQueue(this);
}
private void pollForUpdates(){
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
displayData();
Intent intent = new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("DATAPASSED", g);
sendBroadcast(intent);
}catch (Exception e){
}
}
},0,UPDATE_INTERVAL);
}
/*------------------------- get data-----------------------*/
public void displayData() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
JSONArray scale = response.getJSONArray("scale");
for (int i = 0; i < scale.length(); i++) {
JSONObject scale = scale.getJSONObject(i);
String id = scale.getString("id");
if(id.equals("00001")) {
String weight = scale.getString("weight");
g=Integer.parseInt(weight);
if(g==1 && !noti){
PushNotification();
noti=true;
}else if(g!=1 && noti){
noti=false;
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
public void PushNotification()
{
NotificationManager nm = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
//set
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_stat_name);
builder.setContentText("Contents");
builder.setContentTitle("title");
builder.setAutoCancel(true);
builder.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.build();
nm.notify((int)System.currentTimeMillis(),notification);
}
@Override
public void onDestroy() {
super.onDestroy();
if(timer!=null){
timer.cancel();
}
Toast.makeText(this, "Service Stopped...", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
public class MyBinder extends Binder{
Myservice2 getService(){
return Myservice2.this;
} }
}
MainActivity
public class MainActivity extends AppCompatActivity {
private Myservice2 service2;
MyReceiver myReceiver;
TextView weighttxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weighttxt=(TextView) findViewById(R.id.txt_currentweight);
}
@Override
protected void onStart() {
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
Intent intent = new Intent(MainActivity.this,com.thebestsolution.servicemysql.Myservice2.class);
startService(intent);
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(myReceiver);
super.onStop();
}
private class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
int datapassed = arg1.getIntExtra("DATAPASSED", 0);
weighttxt.setText(""+datapassed);
}
}
private void doBinService(){
ServiceConnection cn;
cn=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
service2=((Myservice2.MyBinder)service).getService();
Toast.makeText(MainActivity.this,"Connected",Toast.LENGTH_SHORT).show();
if(service2!=null){
String weight=service2.getWeightString();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
service2=null;
}
};
Intent i=new Intent(this,Myservice2.class);
bindService(i, cn, Context.BIND_AUTO_CREATE);
}
@Override
protected void onResume() {
Log.d("activity", "onResume");
if (service2 == null) {
doBinService();
}
super.onResume();
}
@Override
protected void onPause() {
if (service2 != null) {
// unbindService(myConnection);
service2 = null;
}
super.onPause();
}
}