Gabrio
Gabrio

Reputation: 388

Get Notification from Asynctask process

I need to send notification from a background process. In this project I've tried to send a simple notification every 10 seconds. it runs but doesn't send the notification!

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Long previousDate = new Long(System.currentTimeMillis());
        NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        new GetMethodEx1().execute(previousDate);
    }

    class GetMethodEx1 extends AsyncTask<Long,Void,Void>{

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

        @Override
        protected Void doInBackground(Long... params){
            Long previousDate = params[0];
            Long Intervall = new Long(System.currentTimeMillis());
            while ( true ){
                if ((Intervall - previousDate) > 10000 ){
                    String title = "Title";
                    String body = "Hi, I am the body";
                    createNotification( title, body);
                    previousDate = Intervall;
                }
            }
            return null;
        }

        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);
        }
  // [ ... ]
  }

it don't crash but doesn't work!

Upvotes: 3

Views: 5722

Answers (2)

Tim Schumacher
Tim Schumacher

Reputation: 421

Given Gabrio's question and Sash_KP answer, I wanted to supply the concepts as cleaned up code here:

https://github.com/tks423/glendale-case-detail-app

public class MainActivity extends AppCompatActivity {

private EditText respText;
private static final String siteUrlSansActivityId = "https://csi.glendaleca.gov/csipropertyportal/jsp/frameContent.jsp?actStatus=Case&actId=";
private String siteUrl;
private EditText activityId;
private Context mContext  = MainActivity.this;
private int NOTIFICATION_ID = 1;
private Notification noti;
private NotificationManager nm;
PendingIntent contentIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    activityId = (EditText) findViewById(R.id.edtURL);

    activityId.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {

            siteUrl = siteUrlSansActivityId + activityId.getText().toString();
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        public void onTextChanged(CharSequence s, int start, int before, int count) {}
    });

    Button btnGo = (Button) findViewById(R.id.btnGo);
    respText = (EditText) findViewById(R.id.edtResp);
    btnGo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            try {

                Log.d("JSwa", "Connecting to [" + siteUrl + "]");
                Document doc  = Jsoup.connect(siteUrl).get();
                // Get document (HTML page) title
                String title = doc.title();
                Log.d("JSwA", "Title ["+title+"]");

                Elements topicList = doc.select("td.tabletext");

                String status = topicList.get(1).text();

                respText.setText(status);
            }
            catch(Throwable t) {
                t.printStackTrace();
            }

        }
    });

    nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    ( new ParseURLLoop() ).execute(siteUrl);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private class ParseURLLoop extends AsyncTask<String, Void, Void> {

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

        //String siteUrl = params[0];

        Long previousDate = new Long(System.currentTimeMillis());
        Log.d("doInBackground", "PreviousDate [" + previousDate + "]");
        Long intervall = new Long(System.currentTimeMillis());
        Log.d("doInBackground", "intervall [" + intervall + "]");

        Boolean a = false;
        while ( a == false){
            if ((intervall - previousDate) > 1000 * 60 ){

                StringBuffer buffer = new StringBuffer();
                try {
                    Log.d("JSwa", "In here");

                    Log.d("JSwa", "Connecting to [" + siteUrl + "]");
                    Document doc  = Jsoup.connect(siteUrl).get();
                    Log.d("JSwa", "Connected to [" + siteUrl + "]");
                    // Get document (HTML page) title
                    String title = doc.title();
                    Log.d("JSwA", "Title ["+title+"]");

                    Elements topicList = doc.select("td.tabletext");

                    if(!"In Process".equals(topicList.get(1).text())){
                        Log.d("Status", "status is [" + topicList.get(1).text() +"]");

                        createNotification( "Glendale AE" , topicList.get(1).text() , MainActivity.this);

                        Intent notificationIntent = new Intent(mContext.getApplicationContext(), MainActivity.class);
                        contentIntent = PendingIntent.getActivity(mContext.getApplicationContext(),
                                0, notificationIntent,
                                PendingIntent.FLAG_CANCEL_CURRENT);
                    }
                }
                catch(Throwable t) {
                    t.printStackTrace();
                }

                previousDate = intervall;
            }
            intervall = new Long(System.currentTimeMillis());
        }

        return null;
    }

    private void createNotification(String contentTitle, String contentText,Context context) {

        Log.d("createNotification", "title is [" + contentTitle +"]");

        nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        //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);


        //Show the notification
        nm.notify(NOTIFICATION_ID, builder.build());
    }



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

}

}

Upvotes: 0

Sash_KP
Sash_KP

Reputation: 5591

In your createNotification() method you need to modify your code to

private void createNotification(String contentTitle, String contentText) {

    mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    //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);


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

And in your onCreate you don't require this line

NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

So remove the above line.

Edit

As you are calling getSystemService inside createNotification() method but not onCreate(), so you need to pass the Context as an argument to the method createNotification(),because getSystemService is a method of the class Context, so you'll need to run it on a context.

private void createNotification(String contentTitle, String contentText,Context context) {

    mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    //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);


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

And while calling the method createNotification() use

createNotification( c, b,MainActivity.this);

Upvotes: 1

Related Questions