我在下面的代码中调用asynctask并生成通知
package apps.skripsi.petvac.navigationmenu;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.client.ClientProtocolException;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import apps.skripsi.petvac.MainMenu.MainMenuAdapter;
import apps.skripsi.petvac.R;
import apps.skripsi.petvac.Services.RegisterUserClass;
import apps.skripsi.petvac.addpetdata.MainAddPetDataActivity;
import apps.skripsi.petvac.notification.NotificationButtonReceiver;
import apps.skripsi.petvac.parser.JSONParser;
import apps.skripsi.petvac.petinformation.MainPetInformation;
import apps.skripsi.petvac.preference.PreferencesHelper;
/**
* Created by widi on 9/9/2015.
*/
public class MainMenu extends Fragment {
FloatingActionButton FAB;
JSONObject json;
JSONObject jsonObject;
PreferencesHelper pref;
ProgressDialog loading;
ImageView iv;
ProgressDialog progress;
NotificationManager mNotificationManager;
SwipeRefreshLayout mSwipeRefreshLayout = null;
ListView list;
TextView tv;
int days;
String result, result2;
String sisaWaktu, sisa_hari;
String ID_USER, ID_BINATANG, NAMA_BINATANG, JENIS_BINATANG, FOTO_BINATANG, RAS_BINATANG, TANGGAL_VAKSIN, NAMA_VAKSIN, STATUS_VAKSIN, ID_DATA_WAKTU_VAKSINASI;
ArrayList<HashMap<String, String>> listBinatang = new ArrayList<HashMap<String, String>>();
public static String id_user = "id_user";
public static String id_binatang = "id_binatang";
public static String nama_binatang = "nama_binatang";
public static String jenis_binatang = "jenis_binatang";
public static String foto_binatang = "foto_binatang";
public static String ras_binatang = "ras_binatang";
public static String tanggal_vaksin = "tanggal_vaksin";
public static String nama_vaksin = "nama_vaksin";
public static String jumlah_hari;
public static String status_vaksin = "status_vaksin";
public static String id_data_waktu_vaksinasi = "id_data_waktu_vaksinasi";
private Context context;
private static String url = "http://petvaccination.hol.es/api/data_menu_utama_vaksinasi.php";
private static String urlgambar = "http://petvaccination.hol.es/imgupload/uploadedimages/";
private static String delete_url = "http://petvaccination.hol.es/UserRegistration/delete_binatang.php";
public MainMenu() {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.main_menu_fragment, container, false);
FAB = (FloatingActionButton) v.findViewById(R.id.buttonTambahData);
mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.activity_main_swipe_refresh_layout);
pref = new PreferencesHelper(getActivity().getBaseContext());
tv = (TextView) v.findViewById(R.id.textView);
list = (ListView) v.findViewById(R.id.list_hewan);
FAB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent a = new Intent(getActivity(), MainAddPetDataActivity.class);
startActivity(a);
}
});
try {
new DataBinatangOperation().execute(url).get(20000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new DataBinatangOperation().execute(url);
updateList();
}
});
return v;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
private void updateList() {
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
private class DataBinatangOperation extends AsyncTask<String, Void, String> {
MainMenuAdapter adapter = new MainMenuAdapter(MainMenu.this,
listBinatang);
@Override
protected String doInBackground(String... params) {
JSONArray json;
try {
result = JSONParser.getPage(url);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
tv.setVisibility(View.GONE);
result2 = pref.getPreferences("json");
try {
System.out.print("result = " + result);
json = new JSONObject(result);
progress.dismiss();
JSONArray objek = json.getJSONArray("data_vaksinasi_menu");
for (int i = 0; i < objek.length(); i++) {
JSONObject jo = objek.getJSONObject(i);
ID_USER = jo.getString(id_user);
ID_BINATANG = jo.getString(id_binatang);
NAMA_BINATANG = jo.getString(nama_binatang);
JENIS_BINATANG = jo.getString(jenis_binatang);
FOTO_BINATANG = jo.getString(foto_binatang);
RAS_BINATANG = jo.getString(ras_binatang);
ID_DATA_WAKTU_VAKSINASI = jo.getString(id_data_waktu_vaksinasi);
TANGGAL_VAKSIN = jo.getString(tanggal_vaksin);
NAMA_VAKSIN = jo.getString(nama_vaksin);
STATUS_VAKSIN = jo.getString(status_vaksin);
if (pref.getPreferences("ID").equals(ID_USER)) {
if (jo.isNull(id_data_waktu_vaksinasi) && jo.isNull(tanggal_vaksin) && jo.isNull(nama_vaksin) && jo.isNull(status_vaksin)) {
NAMA_VAKSIN = "belum ada data";
sisaWaktu = "";
} else {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar waktuSekarang = Calendar.getInstance();
Date date1 = waktuSekarang.getTime();
Date date2 = new Date();
date2 = formatter.parse(TANGGAL_VAKSIN);
if (date2.after(date1)) {
days = Days.daysBetween(new DateTime(date1), new DateTime(date2)).getDays();
if (days > 7 && days <= 30) {
int weeks = days / 7;
sisa_hari = String.valueOf(days);
sisaWaktu = String.valueOf(weeks) + " minggu";
} else if (days > 30 && days <= 365) {
int months = days / 30;
sisa_hari = String.valueOf(days);
sisaWaktu = String.valueOf(months) + " bulan";
} else if (days > 365) {
int years = days / 365;
sisa_hari = String.valueOf(days);
sisaWaktu = String.valueOf(years) + " tahun";
} else {
sisaWaktu = String.valueOf(days) + " hari";
if (days <= 5) {
sisa_hari = String.valueOf(days);
Log.d("result = ", result);
Log.d("result 2 = ", result2);
createSimpleNotification(context, NAMA_BINATANG, sisa_hari, ID_BINATANG);
}
}
} else if (date2.before(date1)) {
days = Days.daysBetween(new DateTime(date2), new DateTime(date1)).getDays();
if (days == 0) {
sisaWaktu = "sekarang";
sisa_hari = String.valueOf(days);
if (STATUS_VAKSIN.equals("belum")) {
createButtonNotification(context, NAMA_BINATANG, sisaWaktu, sisa_hari, ID_BINATANG, ID_DATA_WAKTU_VAKSINASI);
}/*else{
return;
}*/
} else {
sisaWaktu = "lewat " + String.valueOf(days) + " hari";
sisa_hari = String.valueOf(days);
if (STATUS_VAKSIN.equals("belum")) {
createButtonNotification(context, NAMA_BINATANG, sisaWaktu, sisa_hari, ID_BINATANG, ID_DATA_WAKTU_VAKSINASI);
}
}
}
}
}
HashMap<String, String> map = new HashMap<String, String>();
map.put(id_binatang, ID_BINATANG);
map.put(nama_binatang, NAMA_BINATANG);
map.put(jenis_binatang, JENIS_BINATANG);
map.put(foto_binatang, urlgambar + FOTO_BINATANG);
map.put(ras_binatang, RAS_BINATANG);
map.put(tanggal_vaksin, sisaWaktu);
map.put(jumlah_hari, sisa_hari);
map.put(nama_vaksin, NAMA_VAKSIN);
if (pref.getPreferences("ID").equals(ID_USER)) {
listBinatang.add(map);
System.out.println("hasil list : " + String.valueOf(listBinatang));
}
}
if (String.valueOf(listBinatang).equals("[]")) {
tv.setVisibility(View.VISIBLE);
}
System.out.println("adapter : " + String.valueOf(adapter));
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long idx) {
HashMap<String, String> ambilid = new HashMap<String, String>();
ambilid = listBinatang.get(position);
Toast.makeText(getActivity(), "pindah halaman", Toast.LENGTH_SHORT).show();
Intent a = new Intent(getActivity(), MainPetInformation.class);
Log.d("sisa ", ambilid.get(MainMenu.jumlah_hari));
a.putExtra("IDB", ambilid.get(MainMenu.id_binatang));
a.putExtra("IDVAK", ambilid.get(MainMenu.id_data_waktu_vaksinasi));
a.putExtra("SW", ambilid.get(MainMenu.jumlah_hari));
startActivity(a);
}
});
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> ambilid = new HashMap<String, String>();
ambilid = listBinatang.get(position);
final String idbin = ambilid.get(MainMenu.id_binatang);
Log.d("idb ", idbin);
AlertDialog.Builder ab = new AlertDialog.Builder(getActivity());
ab.setTitle("Delete Binatang");
ab.setMessage("Anda Yakin?");
ab.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
delete(idbin);
new DataBinatangOperation().execute(url);
}
});
ab.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.show();
return true;
}
});
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
listBinatang.clear();
adapter.notifyDataSetChanged();
pref.savePreferences("json", result);
progress = ProgressDialog.show(getActivity(), "Please Wait",
"Loading Data", true);
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
public void createSimpleNotification(Context context, String nama_binatang, String sisa_hari, String id) {
Intent resultIntent = new Intent(context, MainPetInformation.class);
resultIntent.putExtra("IDB", id);
resultIntent.putExtra("SW", sisa_hari);
resultIntent.putExtra("IDVAK", "");
mNotificationManager = (NotificationManager) context.getSystemService(getActivity().NOTIFICATION_SERVICE);
int IntID = Integer.valueOf(id);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
PendingIntent resultPending = PendingIntent.getActivity(context, IntID, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setContentTitle(nama_binatang)
.setContentText(sisa_hari + " hari lagi")
.setSound(uri)
.setContentIntent(resultPending);
mNotificationManager.notify(IntID, mBuilder.build());
}
public void createButtonNotification(Context context, String nama_binatang, String sisa_waktu, String sisa_hari, String idb, String idv) {
Log.d("idb", idb);
int IntID = Integer.valueOf(idb);
int sisaHari = Integer.valueOf(sisa_hari);
String sisa_hari2;
Intent intent = new Intent(getActivity(), MainPetInformation.class);
intent.putExtra("IDB", idb);
intent.putExtra("IDVAK", idv);
if (sisaHari > 0) {
sisa_hari2 = "-" + sisa_hari;
intent.putExtra("SW", sisa_hari2);
} else if (sisaHari == 0) {
intent.putExtra("SW", sisa_hari);
}
Intent cancelIntent = new Intent(getActivity(), NotificationButtonReceiver.class);
cancelIntent.putExtra("notifID", IntID);
mNotificationManager = (NotificationManager) context.getSystemService(getActivity().NOTIFICATION_SERVICE);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
PendingIntent IntentAccept = PendingIntent.getActivity(getActivity(), IntID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent IntentCancel = PendingIntent.getActivity(getActivity(), IntID, cancelIntent, 0);
// Building the notifcation
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.logo)
.setContentTitle(nama_binatang)
.setContentText(sisa_waktu)
.setSound(uri)
.addAction(R.drawable.accept, "Accept", IntentAccept)
.addAction(R.drawable.cancel, "Cancel", IntentCancel);
nBuilder.setAutoCancel(true);
mNotificationManager.notify(IntID, nBuilder.build());
}
private void delete(String idbinatang) {
class RegisterUser extends AsyncTask<String, Void, String> {
RegisterUserClass ruc = new RegisterUserClass();
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(getActivity(), "Please Wait", null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("id_binatang", params[0]);
String result = ruc.sendPostRequest(delete_url, data);
Log.d("result ", result);
return result;
}
}
RegisterUser ru = new RegisterUser();
ru.execute(idbinatang);
}
}
但每次刷新或更改活动时,它都会再次更新新数据并继续生成通知,即使json数据尚未更改。
如果json没有改变,有人可以给我一个如何让它不会更新数据的解决方案吗?
答案 0 :(得分:0)
以下是我的提示,希望它们将成为您的解决方案:
您的问题:您希望AsyncTask不调用api,因为来自服务器的json或数据是相同的。
我的回答:你不能这样做,因为,基本上,AsyncTask用于后台任务,就像你在这里一样,从服务器获取数据。希望它能帮助你更好地理解。