PotatoesPower
PotatoesPower

Reputation: 94

Call ASyncTask for notification

I want use AsyncTask on my app for sending notification to my user when on a website, the JSON Value =\= false.

The AsyncTask is as:

public class ASyncTask extends AsyncTask<String, Void, String> {

  private static boolean onair;
  public static final String TAG = "[NOTIF]"; 
  private final static int INTERVAL = 1000; //2 minutes
  Handler mHandler = new Handler();

  private final HttpClient httpclient = new DefaultHttpClient();
  final HttpParams params = httpclient.getParams();
  HttpResponse response;
  private String content =  null;
  private boolean error = false;

  private Context mContext;
  private int NOTIFICATION_ID = 1;
  private Notification mNotification;
  private NotificationManager mNotificationManager;

  Runnable mHandlerTask = new Runnable() {
    @Override
    public void run() {
      detectonline_prepare();
      mHandler.postDelayed(mHandlerTask, INTERVAL);
    }
  };

  public ASyncTask(Context context){
    this.mContext = context;

    //Get the notification manager
    mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

  }

  protected void onPreExecute() {
    Log.i(TAG, "Erreur onPretExecute");
  }

  protected String doInBackground(String... urls) {

    detectonline_prepare();
    return content;
  }

  protected void onCancelled() {
    createNotification("Une erreur s'est produite",content);
  }

  protected void onPostExecute(String content) {
    detectonline_prepare();
    if (error) {
      Log.i(TAG, "Erreur onPostExecute");
    } else {
      Log.i(TAG, "[NOTIF] OK");
      createNotification("ok","ok");
    }
  }

  private void createNotification(String contentTitle, String contentText) {

    //Build the notification using Notification.Builder
    Notification.Builder builder = new Notification.Builder(mContext)
                .setSmallIcon(android.R.drawable.stat_sys_download)
                .setAutoCancel(true)
                .setContentTitle(contentTitle)
                .setContentText(contentText);

    //Get current notification
    mNotification = builder.getNotification();

    //Show the notification
    mNotificationManager.notify(NOTIFICATION_ID, mNotification);
  }

  public void detectonline_prepare(){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    try {
      detectonline();
    } catch (JSONException | IOException e) {
      e.printStackTrace(System.out);
    }
  }

  public void detectonline() throws JSONException, IOException {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    checkIfOnline();

    if (onair == false) {
      Log.i(TAG, "Variable OFF");
    } else {
      //createNotification();
      Log.i(TAG, "Variable ON");
    }
  }

  public static void checkIfOnline() throws JSONException, IOException {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";

    String jsonText = readFromUrl(channerUrl);// reads text from URL

    JSONObject json = new JSONObject(jsonText); // You create a json object from your string jsonText
    if (json.has("onair")) { // just a simple test to check the node that you need existe
      //boolean onair = json.getBoolean("onair"); // In the url that you gave onair value is boolean type
      onair = json.getBoolean("onair");
      return;
    }
 }

 private static String readFromUrl(String url) throws IOException {
   StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
   StrictMode.setThreadPolicy(policy);
   URL page = new URL(url);
   StringBuilder sb = new StringBuilder();
   Scanner scanner = null;
   try {
     scanner = new Scanner(page.openStream());
     while (scanner.hasNextLine()) {
       sb.append(scanner.nextLine());
     }
   } finally {
     if (scanner != null)
        scanner.close();
   }
   return sb.toString();
}

But I want to know how this work. How I can call from my MainActivity this AsyncTask (for this to work in the background).

Thank you

Upvotes: 0

Views: 338

Answers (1)

sumandas
sumandas

Reputation: 565

AsynTask are basically threads that let you do operations in separate thread (non-UI that is the main thread). You don't need AsynTask for notifications, it can be achieved using PendingIntent and Listeners like a phone call, touch listener, etc.

Now coming to your question try this:

In your main thread do the following:

ASynsTask myAsyncTask = new ASyncTask(getApplicationContext());
myAsyncTask.execute();

Tutorial: Good read

Upvotes: 1

Related Questions