Android通知onclick

时间:2016-12-30 10:58:12

标签: android android-intent notifications android-pendingintent

我想知道如何为Android通知实现onClickListener。我正在尝试在通知中实现sendText(),而不是将用户发送到主要活动:

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);
            }
        }
    }
}

请注意,以下信息并非真正必要。这主要是因为stackoverflow认为我的代码与文本比率太低,但也可能有助于澄清一点:

sendText()基本上是一种尝试在不打开新活动的情况下发送预制文本消息的方法。但是,如果权限不存在,那么它将使用intent打开新活动。因此,为了尽量减少屏幕上的数量并使用户最容易,我尝试使用sendtext方法。

3 个答案:

答案 0 :(得分:1)

如果您不想将用户发送到活动,那么您可以在用户点击通知时启动服务:PendingIntent.getService(...)并执行作业以在那里发送文字。

答案 1 :(得分:0)

试试这个:

    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);
 }

}

答案 2 :(得分:0)

您可以创建pendingIntent来触发广播接收器,而不是创建pendingIntent来启动Activity,如下所示

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

因此,当您单击通知时,它将调用您的BroadCast接收器 SendTextReceiver 并在其中执行您的sendText逻辑,因此通过这种方式您不必始终启动活动并且您的逻辑将在没有活动