android - 在 Android 上获取 MYSQL 更新通知

标签 android mysql push-notification android-service android-notifications

如何在远程数据库中的每次更新时向用户发送通知。我想通知用户是否添加了任何新行或更新了现有行。我正在使用自定义 ListView 并希望显示 BigPictureStyle 通知。

public class EventServices extends Service {
int numMessages = 0;
String rowCount = null;
int oldRowCount = 0;
HashMap<String,String> hashMap = new HashMap<>();

String rowCountLink = "http://192.168.0.101/getdbrowcount.php";

public EventServices() {

}

@Override
public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onCreate() {
    Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
    oldRowCount = Integer.parseInt(getRowCount());

}



@Override
public void onStart(Intent intent, int startId) {

    Log.d("Parse","Old row count: "+ oldRowCount);
    Log.d("Parse","New row count: "+Integer.parseInt(getRowCount()));


    if(Integer.parseInt(getRowCount())> oldRowCount) {


        String newEventLink =  "http://192.168.0.101/getnewevent.php";

        new MyTask(newEventLink).execute();
        //  NewEventDetails newED = new NewEventDetails();
        // NewEventHashMap newEventHashMap = new NewEventHashMap();


        String name = hashMap.get("name");
        String description = hashMap.get("description");
        String image = hashMap.get("image");

        Log.d("Parse","New event name: "+name);
        Log.d("Parse","New event description: "+description);
        Log.d("Parse","New event image: "+image);



        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        Intent resultIntent = new Intent(this, ItemDetailActivity.class);
         resultIntent.putExtra("description",description);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
        resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder mNotifyBuilder;
        NotificationManager mNotificationManager;
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // Sets an ID for the notification, so it can be updated
        int notifyID = 9001;

        mNotifyBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(name)
                .setContentText(description)
                .setSmallIcon(R.drawable.icon);
        // Set pending intent


    //    startActivity(resultIntent);
      //  mNotifyBuilder.setContentIntent()
        mNotifyBuilder.setContentIntent(resultPendingIntent);
        // Set Vibrate, Sound and Light
        int defaults = 0;
        defaults = defaults | Notification.DEFAULT_LIGHTS;
        defaults = defaults | Notification.DEFAULT_VIBRATE;
        defaults = defaults | Notification.DEFAULT_SOUND;
        mNotifyBuilder.setDefaults(defaults);
        // Set the content for Notification
        //  mNotifyBuilder.setContentText(intent.getStringExtra("intntdata"));
        // Set autocancel
        mNotifyBuilder.setAutoCancel(true);
        // Post a notification
        mNotificationManager.notify(notifyID, mNotifyBuilder.build());
        oldRowCount++;

    }else{

    }
}

@Override
public void onDestroy() {
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

}


private String getRowCount(){

    RowCountDownloader rowCountDownloader = new RowCountDownloader(rowCountLink);

    try {
        rowCount   = rowCountDownloader.execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
  //  Log.d("Parse","Rowcount in services: "+rowCount);
    return  rowCount;
}


class MyTask extends AsyncTask<Void,Integer,String> {

    String newEventLink;
   // HashMap<String,String> hashMap = new HashMap<>();




    public MyTask( String newEventLink){
        this.newEventLink = newEventLink;

    }

    @Override
    protected String doInBackground(Void... params) {

        String data = downloadData();

        return  data;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {


    }

    private String downloadData() {
        String line = null;
        InputStream inputStream =null;
        try{
            URL url = new URL(newEventLink);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            inputStream = new BufferedInputStream(con.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer sb = new StringBuffer();

            if (br != null) {
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } else {
                return null;
            }
            try{
                JSONObject jo = new JSONObject(sb.toString());
                JSONArray ja = jo.getJSONArray("result");
                JSONObject obj = ja.getJSONObject(0);

                hashMap.put("name",obj.getString("name"));
                hashMap.put("description",obj.getString("description"));
                hashMap.put("image",obj.getString("image"));


           }catch (JSONException e){
                e.printStackTrace();
            }
            return null;

        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try{
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return null;
      }
    }





  }

每当创建新服务时,它都会从表中获取行总数(COUNT(*)),然后存储在变量中,然后下次服务从 php 脚本检查更新的行计数,然后将其与现有行进行比较数数。 如果新行数大于现有行数,则它将从数据库中获取数据(SELECT * from table where id = (SELECT COUNT(*) FROM table))。它将仅返回新行,然后显示通知。

但我的问题是它在来自远程数据库的新数据之前显示通知。可能是因为我正在从服务器下载图像。那么,如何解决这个问题呢?

最佳答案

经过大量研究,我解决了这个问题。我将下载数据的所有代码放在 doInBackground() 中,然后将结果传递到 onPostExecute 中,我已将其显示在通知上。

关于android - 在 Android 上获取 MYSQL 更新通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38941877/

相关文章:

android - MyFirstApp Android 编码教程中的错误“Intent 构造函数未定义。

android - 为什么 RecyclerView.OnScrollListener 不是接口(interface)而是抽象类?

android - 为什么我的旧平板电脑不支持混合应用程序中的某些 css 行?

ios - 更新后,iOS应用程序从通知中心消失

带有app后台的iOS远程推送通知

Android - 拍摄照片并通过 Intent 使用自定义名称将其保存到自定义目的地

python - Django 应用程序在迁移到 heroku MySQL ClearDB 时抛出 MigrationSchemaMissing

php - 来自 MySQL DB 的 AngularJS 值

mysql - 如何重复不同的图片?

android - 查明当应用程序在后台时收到 Firebase 消息的时间