Tal C
Tal C

Reputation: 567

Android notification onclick

I was wondering how to implement the onClickListener for an android notification. I am trying to implement sendText() in the notification instead of sending the user to the main activity:

public class AlertReceiver extends BroadcastReceiver {
    Context mContext;
    String number;
    String messageList;
    String name;
    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        name = intent.getStringExtra("name");
        messageList = intent.getStringExtra("messageList");
        number = intent.getStringExtra("number");

        createNotification(context, "times up " + name, "5 seconds passed!", "alert");
    }
    public void createNotification(Context context, String message, String messageText, String messageAlert){
        PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(message)
                .setTicker(messageText)
                .setContentText(messageAlert);
        mBuilder.setContentIntent(notificIntent);
        mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
    }

    public void sendText(){


        //Turn string of all messages into an ArrayList in order to get one specific message at random
        ArrayList<String> messagesArrayList = null;
        try {
            messagesArrayList = Utility.getArrayListFromJSONString(messageList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Random rand = new Random();

        //todo the following may cause a bug if there are no messages in list
        int  n = rand.nextInt(messagesArrayList.size());



        String message = messagesArrayList.get(n);

        try {

            //send text message
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number, null, message, null, null);
            Toast.makeText(mContext, "Message Sent",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception ex) {

            //If text message wasn't sent attempt to send text another way (through the user's text messaging app)
            // Most likely due to text message permissions not being accepted by user
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("smsto:" + number));  // This ensures only SMS apps respond
            intent.putExtra("sms_body", message);
            if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        }
    }
}

Note the following information is not really necessary. It is mainly because stackoverflow thinks my code to text ratio is too low but also may help clarify a little bit:

The sendText() is basically a method that tries to send a pre-made text message without opening up a new activity. However, if permissions aren't there then it will open up the new activity using an intent. So in an effort to minimize amount of screens coming up and make it easiest on the user I tried to do it using the sendtext method.

Upvotes: 0

Views: 8719

Answers (3)

Hasif Seyd
Hasif Seyd

Reputation: 1694

Instead of creating a pendingIntent to start an Activity, you can create a pendingIntent to fire a Broadcast receiver as shown below

PendingIntent intent = PendingIntent.getBroadcast(context, 0, new Intent(context, SendTextReceiver.class), 0);

so when you click notification, it will invoke your BroadCast receiver SendTextReceiver and do your sendText logic inside it, so by this way you dont have to always start an activity and your logic will be done without an activity

Upvotes: 3

rafsanahmad007
rafsanahmad007

Reputation: 23881

Try this:

    public class AlarmReceiver extends BroadcastReceiver {

 private static final int MY_NOTIFICATION_ID=1;
 NotificationManager notificationManager;
 Notification myNotification;

 @Override
 public void onReceive(Context context, Intent intent) {

     // here DoSomething is your service name that you want to start
     Intent myIntent = new Intent(context, DoSomething.class);
     PendingIntent pendingIntent = PendingIntent.getService(
            context, 
            0, 
            myIntent, 
            0);

     myNotification = new NotificationCompat.Builder(context)
       .setContentTitle("Exercise of Notification!")
       .setContentText("Do Something...")
       .setTicker("Notification!")
       .setWhen(System.currentTimeMillis())
       .setContentIntent(pendingIntent)
       .setDefaults(Notification.DEFAULT_SOUND)
       .setAutoCancel(true)
       .setSmallIcon(R.drawable.ic_launcher)
       .build();

     notificationManager = 
       (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
     notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
 }

}

Upvotes: 0

Andy Res
Andy Res

Reputation: 16043

If you don't want to send the user to an Activity, then you can fire a service: PendingIntent.getService(...) when user clicks on the notification and do the job to send the text there.

Upvotes: 1

Related Questions