改写
正如我们之前讨论过的,您希望强制通知的tickerText
自动换行。一种方法是将文本分成适当长度的行并为每一行发送通知:
public class Example extends Activity {
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("Example", "Alarm received");
sendNotification();
}
}
AlarmManager alarmManager;
NotificationManager notificationManager;
AlarmReceiver alarmReceiver = new AlarmReceiver();
Notification notification = new Notification();
Intent notificationIntent;
PendingIntent pendingIntent;
int tickerIndex = 0;
List<String> tickerTexts = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Determine the screen width and density, split tickerText appropriately
String tickerText = "A tickerText that is long enough to cause a word wrap in portrait.";
tickerTexts.add(tickerText.substring(0, 35));
tickerTexts.add(tickerText.substring(35));
notificationIntent = new Intent(this, Example.class);
pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
notification.icon = android.R.drawable.star_on;
sendNotification();
registerReceiver(alarmReceiver, new IntentFilter("Generic"));
}
@Override
protected void onDestroy() {
unregisterReceiver(alarmReceiver);
super.onDestroy();
}
public void sendNotification() {
Log.v("Example", "Send Notification " + tickerIndex);
notification.tickerText = tickerTexts.get(tickerIndex);
notification.setLatestEventInfo(this, "Title", "Text " + tickerIndex, pendingIntent);
notificationManager.cancel(0);
notificationManager.notify(0, notification);
tickerIndex++;
if(tickerIndex < tickerTexts.size()) {
Log.v("Example", "Setting up alarm");
PendingIntent alarmPending = PendingIntent.getBroadcast(this, 0, new Intent("Generic"), 0);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, alarmPending);
}
}
}
但是你可以看到我跳过了设置的一个组成部分:我假设了适合的文本长度,我没有计算它。为了确定合适的断点,您需要计算屏幕的宽度、字体的缩放大小和密度。您还需要考虑“!!!” 可能比“www”短,具体取决于字体,并且用户可以在横向和纵向之间切换......您可以查看源代码以了解通用 Android 如何分解tickerText。
无论如何,强制tickerText 自动换行可能比压缩原始字符串或向“非包装”电话制造商发送愤怒的信件更复杂。