【发布时间】:2016-12-30 10:58:12
【问题描述】:
我想知道如何为 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() 基本上是一种尝试发送预制文本消息而不打开新活动的方法。但是,如果权限不存在,那么它将使用意图打开新活动。因此,为了尽量减少出现的屏幕数量并使用户最容易使用,我尝试使用 sendtext 方法来实现。
【问题讨论】:
标签: android android-intent notifications android-pendingintent