私はonClickListener
をAndroidの通知のために実装する方法を知りました。私の代わりに、メインの活動にユーザーを送信する通知にsendText()
を実装しようとしています:Android通知onclick
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
メソッドを使ってやろうとしました。